def merge_cols():
"""
合并列
:return:
"""
data_1 = [
["a", 11],
["b", 12],
["c", 13],
["d", 14],
["e", 15]
]
data_2 = [
["a", 'col-31', 'col-41'],
["b", 'col-32', 'col-42'],
["c", 'col-33', 'col-43'],
["d", 'col-34', 'col-44'],
["e", 'col-35', 'col-45']
]
columns_1 = ['col-1', 'col-2']
columns_2 = ['col-1', 'col-3', 'col-4']
index = ['idx-1', 'idx-2', 'idx-3', 'idx-4', 'idx-5']
df_1 = pd.DataFrame(data=data_1, index=index, columns=columns_1)
df_2 = pd.DataFrame(data=data_2, index=index, columns=columns_2)
# 合并
merge_1 = pd.merge(df_1, df_2, on="col-1")
merge_2 = pd.merge(df_1, df_2)
print(merge_1)
print(merge_2)
merge_1、merge_2 返回结果:
col-1 col-2 col-3 col-4
0 a 11 col-31 col-41
1 b 12 col-32 col-42
2 c 13 col-33 col-43
3 d 14 col-34 col-44
4 e 15 col-35 col-45
def merge_rows():
"""
合并行
:return:
"""
data_1 = [
[11, 12, 13, 14],
[21, 22, 23, 24],
[31, 32, 33, 34],
[41, 42, 43, 44],
[51, 52, 53, 54]
]
data_2 = [
[141, 142, 143, 144],
[151, 152, 153, 154]
]
columns = ['col-1', 'col-2', 'col-3', 'col-4']
index = ['idx-1', 'idx-2', 'idx-3', 'idx-4', 'idx-5']
df_1 = pd.DataFrame(data=data_1, index=index, columns=columns)
df_2 = pd.DataFrame(data=data_2, index=["idx-101", "idx-102"], columns=columns)
# 插入单行
df = df_1.append(df_2)
print(df)
df 返回结果:
col-1 col-2 col-3 col-4
idx-1 11 12 13 14
idx-2 21 22 23 24
idx-3 31 32 33 34
idx-4 41 42 43 44
idx-5 51 52 53 54
idx-101 141 142 143 144
idx-102 151 152 153 154