用同一列组合两个数据帧

2024-09-29 23:32:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧

  1. feelingsDF'feeling', 'count', 'code'
  2. countryDF'feeling', 'countryCount'

如何创建另一个数据帧,从countryDF中获取列,并将其与feelingsDF中的code列相结合

我猜您可能需要以某种方式使用feelingsDF中相同的feeling列来组合它们并进行匹配,确保相同的code匹配相同的感觉

我希望这三列显示为:

[feeling][countryCount][code]

Tags: 数据count方式code感觉feelingcountrycountcountrydf
2条回答

您通过“feeling”列连接两个数据帧。假设您只需要两个数据帧共用的“feeling”中的条目,那么您需要进行内部联接

下面是一个具有两个dfs的类似示例:

x = pd.DataFrame({'feeling': ['happy', 'sad', 'angry', 'upset', 'wow'], 'col1': [1,2,3,4,5]})
y = pd.DataFrame({'feeling': ['okay', 'happy', 'sad', 'not', 'wow'], 'col2': [20,23,44,10,15]})
x.merge(y,how='inner', on='feeling')

输出:

  feeling  col1  col2
0   happy     1    23
1     sad     2    44
2     wow     5    15

要删除“count”列,请选择feelingsDF的其他列,然后按“countryCount”列排序。请注意,这将使索引失去顺序,但您可以在之后重新为组合的_df编制索引

combined_df = feelingsDF[['feeling', 'code']].merge(countryDF, how='inner', on='feeling').sort_values('countryCount')
# To reset the index after sorting:
combined_df = combined_df.reset_index(drop=True)

可以使用pd.merge连接两个数据帧。假设您想加入感觉列,您可以使用:

df= pd.merge(feelingsDF, countryDF, on='feeling', how='left')

有关pd.merge,请参见documentation,以了解如何使用on和how参数

feelingsDF = pd.DataFrame([{'feeling':1,'count':10,'code':'X'}, 
{'feeling':2,'count':5,'code':'Y'},{'feeling':3,'count':1,'code':'Z'}])

   feeling  count code
0        1     10    X
1        2      5    Y
2        3      1    Z

countryDF = pd.DataFrame([{'feeling':1,'country':'US'},{'feeling':2,'country':'UK'},{'feeling':3,'country':'DE'}])

   feeling country
0        1      US
1        2      UK
2        3      DE

df= pd.merge(feelingsDF, countryDF, on='feeling', how='left')

   feeling  count code country
0        1     10    X      US
1        2      5    Y      UK
2        3      1    Z      DE

相关问题 更多 >

    热门问题