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)
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
您通过“feeling”列连接两个数据帧。假设您只需要两个数据帧共用的“feeling”中的条目,那么您需要进行内部联接
下面是一个具有两个dfs的类似示例:
输出:
要删除“count”列,请选择feelingsDF的其他列,然后按“countryCount”列排序。请注意,这将使索引失去顺序,但您可以在之后重新为组合的_df编制索引
可以使用pd.merge连接两个数据帧。假设您想加入感觉列,您可以使用:
有关pd.merge,请参见documentation,以了解如何使用on和how参数
相关问题 更多 >
编程相关推荐