import pandas as pd
import numpy as np
pandas合并-pd.concat学习记录
这里写了一个创建dataframe的函数
def make_df(cols,ind):
data = {c:[str(c)+str(i) for i in ind] for c in cols}
return pd.DataFrame(data,ind)
- Series的合并
- 默认是行合并,即axis=0
s1=pd.Series(['A','B','C'],index=[1,2,3])
s2=pd.Series(['D','E','F'],index=[4,5,6])
pd.concat([s1,s2])
1 A
2 B
3 C
4 D
5 E
6 F
dtype: object
- 看下axis=1,列合并的情况
pd.concat([s1,s2],axis=1)

- DataFrame合并
df1 = make_df('AB',[1,2])
df2 = make_df('AB',[3,4])
df1

df2

- 默认行合并 axis=0
pd.concat([df1,df2])

- 列合并 axis=1
pd.concat([df1,df2],axis=1)

df3=make_df('AB',[0,1])
df4=make_df('CD',[0,1])
df3

df4

pd.concat([df3,df4],axis=1)

说明,行合并,那么只有行索引一致,才能合并,列同理
- 忽略重复索引情况
x=make_df('AB',[0,1])
y=make_df('AB',[2,3])
y.index=x.index
x

y

pd.concat([x,y])

pd.concat([x,y],ignore_index=True)

pd.concat([x,y],ignore_index=True,axis=1)

下次继续
网友评论