- 1 函数原型
- 2 常用的参数含义
- 3 举例
pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
keys=None, levels=None, names=None, verify_integrity=False,
copy=True)
2 常用的参数含义
obj
:为Series、DataFrame、Pannel对象的序列或映射。axis
:默认为0,。是沿着连接的轴join
:{“inner”, “outer”},是为内连接和外连接。keys
:使用传递的键值,作为最外才能够构建层次索引。如果为多索引,应该使用元组。
-
效果如下图所示
-
代码
import pandas as pd
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']},
index=[0, 1, 2, 3])
print(df1)
df2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],
'B': ['B4', 'B5', 'B6', 'B7'],
'C': ['C4', 'C5', 'C6', 'C7'],
'D': ['D4', 'D5', 'D6', 'D7']},
index=[4, 5, 6, 7])
print(df2)
df3 = pd.DataFrame({'A': ['A8', 'A9', 'A10', 'A11'],
'B': ['B8', 'B9', 'B10', 'B11'],
'C': ['C8', 'C9', 'C10', 'C11'],
'D': ['D8', 'D9', 'D10', 'D11']},
index=[8, 9, 10, 11])
print(df3)
frames = [df1, df2, df3]
print("frames:\n", frames)
result = pd.concat(frames) # 默认axis=0
print("result:\n", result)
- 扩展1:如果指定
keys
result_1 = pd.concat(frames, keys=['x', 'y', 'z'])
print("result_1:\n", result_1)
- 输出:
result_1:
A B C D
x 0 A0 B0 C0 D0
1 A1 B1 C1 D1
2 A2 B2 C2 D2
3 A3 B3 C3 D3
y 4 A4 B4 C4 D4
5 A5 B5 C5 D5
6 A6 B6 C6 D6
7 A7 B7 C7 D7
z 8 A8 B8 C8 D8
9 A9 B9 C9 D9
10 A10 B10 C10 D10
11 A11 B11 C11 D11
- 扩展2:如果使用
join
import pandas as pd
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']},
index=[0, 1, 2, 3])
print(df1)
df2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],
'B': ['B4', 'B5', 'B6', 'B7'],
'C': ['C4', 'C5', 'C6', 'C7'],
'D': ['D4', 'D5', 'D6', 'D7']},
index=[4, 5, 6, 7])
print(df2)
df3 = pd.DataFrame({'A': ['A8', 'A9', 'A10', 'A11'],
'B': ['B8', 'B9', 'B10', 'B11'],
'C': ['C8', 'C9', 'C10', 'C11'],
'D': ['D8', 'D9', 'D10', 'D11']},
index=[8, 9, 10, 11])
print(df3)
frames = [df1, df2, df3]
print("frames:\n", frames)
result = pd.concat(frames) # 默认axis=0
print("result:\n", result)
result_1 = pd.concat(frames, keys=['x', 'y', 'z'])
print("result_1:\n", result_1)
df4 = pd.DataFrame({'B': ['B2', 'B3', 'B6', 'B7'],
'D': ['D2', 'D3', 'D6', 'D7'],
'F': ['F2', 'F3', 'F6', 'F7']},
index=[2, 3, 6, 7])
result_2 = pd.concat([df1, df4], axis=1)
result_3 = pd.concat([df1, df4], axis=1, join='inner')
print("join前:\n", result_2)
print("join后:\n", result_3)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)