pandas的concat()函数可以用于将多个DataFrame对象按照指定的轴进行合并。

语法: pd.concat(objs, axis=0, join='outer', ignore_index=False)

参数解释:

  • objs:要合并的DataFrame对象的列表或字典。
  • axis:指定合并的轴,0表示按行合并,1表示按列合并。
  • join:指定合并时的连接方式,'outer'表示取并集,'inner'表示取交集。
  • ignore_index:是否忽略原始索引。

示例:

import pandas as pd

# 创建两个DataFrame对象
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df2 = pd.DataFrame({'A': [7, 8, 9], 'B': [10, 11, 12]})

# 按行合并两个DataFrame对象
result = pd.concat([df1, df2], axis=0)
print(result)
# 输出:
#    A   B
# 0  1   4
# 1  2   5
# 2  3   6
# 0  7  10
# 1  8  11
# 2  9  12

# 按列合并两个DataFrame对象
result = pd.concat([df1, df2], axis=1)
print(result)
# 输出:
#    A  B  A   B
# 0  1  4  7  10
# 1  2  5  8  11
# 2  3  6  9  12

# 忽略原始索引
result = pd.concat([df1, df2], axis=0, ignore_index=True)
print(result)
# 输出:
#    A   B
# 0  1   4
# 1  2   5
# 2  3   6
# 3  7  10
# 4  8  11
# 5  9  12

以上示例演示了按行合并和按列合并两个DataFrame对象,并且展示了如何忽略原始索引。

pandas concat使用

原文地址: https://www.cveoy.top/t/topic/h9zW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录