pandas 轴向连接

numpy中提供来用于合并数组的函数

arr = np.arange(12).reshape(3,4)
print(arr)
result = np.concatenate([arr,arr],axis=1)
print(result)

s1 = pd.Series([0,1],index=[‘a’,‘b’])
s2 = pd.Series([2,3,4],index=[‘c’,‘d’,‘e’])
s3 = pd.Series([5,6],index=[‘f’,‘g’])
result = pd.concat([s1,s2,s3])
print(result)
默认是axis = 0 连接成新的Series 如果 把axis = 1 那么会连接成新的DataFrame,输出如下
0 1 2
a 0.0 NaN NaN
b 1.0 NaN NaN
c NaN 2.0 NaN
d NaN 3.0 NaN
e NaN 4.0 NaN
f NaN NaN 5.0
g NaN NaN 6.0

这种连接默认是外连接,我们可以改为join = ‘inner’ 这种方式就像join方法中的 how = 'outer’的方法

s1 = pd.Series([0,1],index=[‘a’,‘b’])
s2 = pd.Series([2,3,4],index=[‘c’,‘d’,‘e’])
s3 = pd.Series([5,6],index=[‘f’,‘g’])
s4 = pd.concat([s1*5,s3])
print(s4)
print(s1)
result = pd.concat([s1,s4],axis=1,join=‘inner’)
print(result)

0 1
a 0 0
b 1 5

s1 = pd.Series([0,1],index=[‘a’,‘b’])
s2 = pd.Series([2,3,4],index=[‘c’,‘d’,‘e’])
s3 = pd.Series([5,6],index=[‘f’,‘g’])
s4 = pd.concat([s15,s3])
print(s4)
print(s1)
result = pd.concat([s1,s1,s3],keys=[‘one’,‘two’,‘three’])
print(result)
通过设置的keys值的方式可以把索引名字相互区分
在设置keys值的时候,如果把axis = 1,那keys值就会变成列头
s1 = pd.Series([0,1],index=[‘a’,‘b’])
s2 = pd.Series([2,3,4],index=[‘c’,‘d’,‘e’])
s3 = pd.Series([5,6],index=[‘f’,‘g’])
s4 = pd.concat([s1
5,s3])
print(s4)
print(s1)
result = pd.concat([s1,s1,s3],keys=[‘one’,‘two’,‘three’],axis= 1)
print(result)
输出为
one two three
a 0.0 0.0 NaN
b 1.0 1.0 NaN
f NaN NaN 5.0
g NaN NaN 6.0

同样的逻辑DataFrame是适用的

df1 = pd.DataFrame(np.arange(6).reshape(3,2),index=[‘a’,‘b’,‘c’],columns=[‘one’,‘two’])
df2 = pd.DataFrame(5+np.arange(4).reshape(2,2),index=[‘a’,‘c’],columns=[‘three’,‘four’])
print(df1)
print(df2)
result = pd.concat([df1,df2],axis=1,keys = [‘level1’,‘level2’])
print(result)
如果传入的不是列表二是一个字典的话,字典的键值会被当作key选项
df1 = pd.DataFrame(np.arange(6).reshape(3,2),index=[‘a’,‘b’,‘c’],columns=[‘one’,‘two’])
df2 = pd.DataFrame(5+np.arange(4).reshape(2,2),index=[‘a’,‘c’],columns=[‘three’,‘four’])
print(df1)
print(df2)
result = pd.concat({‘level1’:df1,‘level2’:df2},axis=1)
print(result)

level1 level2
one two three four
a 0 1 5.0 6.0
b 2 3 NaN NaN
c 4 5 7.0 8.0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值