Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:使用一个公共列合并多个数据帧_Python_Python 3.x_Pandas_Merge_Jointable - Fatal编程技术网

Python 熊猫:使用一个公共列合并多个数据帧

Python 熊猫:使用一个公共列合并多个数据帧,python,python-3.x,pandas,merge,jointable,Python,Python 3.x,Pandas,Merge,Jointable,我正在处理多个数据帧,每个数据帧都有一个公共列,即post_id。每个df的外观示例如下: post_id post_likes 0 1 1 2 2 3 3 4 4 5 5 6 因此,每个df都有一列,其中有post_id,但在每个后续df中还有另一列,如likes、total count、names等。是否有任何方法可以根据post\u id将所有这

我正在处理多个数据帧,每个数据帧都有一个公共列,即post_id。每个df的外观示例如下:

  post_id   post_likes  
  0          1
  1          2
  2          3
  3          4
  4          5
  5          6

因此,每个df都有一列,其中有post_id,但在每个后续df中还有另一列,如likes、total count、names等。是否有任何方法可以根据post\u id将所有这些DF分组为一个,因为我的最终目标是将此数据帧写入csv。

假设我有一个很长的数据帧列表,所有这些数据帧都有一列标记为
post\u id
和另一列

import pandas as pd
df1 = pd.DataFrame(columns=['post_id','post_likes'], data={'post_id': range(6), 'post_likes': range(1,7)})
df2 = pd.DataFrame(columns=['post_id','post_shares'], data={'post_id': range(6), 'post_shares': range(11,17)})
pd.merge(df1,df2,on='post_id')

Out[12]:
   post_id  post_likes  post_shares
0        0           1           11
1        1           2           12
2        2           3           13
3        3           4           14
4        4           5           15
5        5           6           16
lodf = [df1, df2, df3, df4, df5]
您可以使用
pd.concat
将它们放在一起。你只需要先设置索引

df = pd.concat([d.set_index('post_id') for d in lodf], axis=1).reset_index()
演示

df1 = pd.DataFrame(dict(post_id=[1, 2, 3], col1=[1, 2, 3]))
df2 = pd.DataFrame(dict(post_id=[1, 2, 3], col2=[1, 2, 3]))
df3 = pd.DataFrame(dict(post_id=[1, 2, 3], col3=[1, 2, 3]))
df4 = pd.DataFrame(dict(post_id=[1, 2, 3], col4=[1, 2, 3]))
df5 = pd.DataFrame(dict(post_id=[1, 2, 3], col5=[1, 2, 3]))

lodf = [df1, df2, df3, df4, df5]

df = pd.concat([d.set_index('post_id') for d in lodf], axis=1).reset_index()
df

   post_id  col1  col2  col3  col4  col5
0        1     1     1     1     1     1
1        2     2     2     2     2     2
2        3     3     3     3     3     3

​

谢谢我得到了输出wanted@wolverinejohn如果答案解决了你的问题,别忘了接受它。