Python 用同一列组合两个数据帧
我有两个数据帧Python 用同一列组合两个数据帧,python,pandas,dataframe,Python,Pandas,Dataframe,我有两个数据帧 feelingsDF带有列“feeling”、“count”、“code” countryDF带有列'feeling','countryCount' 如何制作另一个数据帧,从countryDF中获取列,并将其与feelingsDF中的code列相结合 我猜您可能需要在feelingsDF中使用相同的feeling列来组合它们并进行匹配,确保相同的code匹配相同的感觉 我希望这三列显示为: [feeling][countryCount][code] 您通过“feeling”列连
feelingsDF
带有列“feeling”、“count”、“code”
countryDF
带有列'feeling','countryCount'
countryDF
中获取列,并将其与feelingsDF
中的code
列相结合
我猜您可能需要在feelingsDF
中使用相同的feeling
列来组合它们并进行匹配,确保相同的code
匹配相同的感觉
我希望这三列显示为:
[feeling][countryCount][code]
您通过“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连接两个数据帧。假设您想加入feeling列,您可以使用:
df= pd.merge(feelingsDF, countryDF, on='feeling', how='left')
有关pd.merge的信息,请参阅,以了解如何使用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
这能解决你的问题吗?你能举一个你尝试过的例子吗?我还没有尝试过,因为我甚至不知道从哪里开始。这是两个数据帧的样子:谢谢!有没有办法去掉“count”列,直接使用“countryCount”?还有,有没有办法通过countryCount查询名单?是的,我更新了我的答案。让我知道这是否有效!