python - 如何连接具有不相等行数和不同列名的数据框

标签 python pandas dataframe

我正在尝试连接四个具有不相等行数和不同列名的数据框。我在这里放置我的代码并输出我得到的结果。

import pandas as pd

data1 = pd.DataFrame({'Col':[33,44,55,67], 'Col1':[44,55,55,555]})
data2 = pd.DataFrame({'Col2':[33,44], 'Col3':[22,22]})
data3 = pd.DataFrame({'Col4':[33,44,44], 'Col5':[22,22,44]})
data4 = pd.DataFrame({'Col6':[33], 'Col7':[22], 'Col8':[44]})


data5 = pd.concat([data1, data2, data3, data4])
data5

这是我的实际输出

enter image description here

我期待的是:

enter image description here

提前致谢

最佳答案

您可以使用 concat使用 axis=1,但首先重复匹配行的最大长度的值:

dfs = [data1, data2, data3, data4]

maxlen = len(max(dfs, key=len))
print (maxlen)
4

dfs = [pd.concat([x] * int(np.ceil(maxlen / len(x))), ignore_index=True).iloc[:maxlen] 
       for x in dfs]
data5 = pd.concat(dfs, axis=1)

print (data5)
   Col  Col1  Col2  Col3  Col4  Col5  Col6  Col7  Col8
0   33    44    33    22    33    22    33    22    44
1   44    55    44    22    44    22    33    22    44
2   55    55    33    22    44    44    33    22    44
3   67   555    44    22    33    22    33    22    44

关于python - 如何连接具有不相等行数和不同列名的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65934592/

相关文章:

python-3.x - Pandas 数据框 : how to count the number of times a variable is repeated in 1 minute

python - 将列拆分为 MultiIndex,在 pandas 中缺少列

python - PNG、GIF 等的 Tensorflow Label_Image

python - 使用nltk进行通用同义词和词性处理

python - 是否可以调试 CherryPy 应用程序?

numpy - 如何将numpy.timedelta64转换为分钟

python数据框到excel

python - pandas dataframe 删除频率较低的行

python - Pandas:添加新的计算(分数)行

python - Pandas,应用函数,它为两行接受两个参数