我有两个数据帧:
第一测向
#df1 -----
location Ethnic Origins Percent(1)
0 Beaches-East York English 18.9
1 Davenport Portuguese 22.7
2 Eglinton-Lawrence Polish 12.0
第二测向
#df2 -----
location lat lng
0 Beaches—East York, Old Toronto, Toronto, Golde... 43.681470 -79.306021
1 Davenport, Old Toronto, Toronto, Golden Horses... 43.671561 -79.448293
2 Eglinton—Lawrence, North York, Toronto, Golden... 43.719265 -79.429765
预期输出:
我想使用#df1
的location列,因为它更干净,并保留所有其他列。我不需要位置栏上的城市、国家信息。你知道吗
location Ethnic Origins Percent(1) lat lng
0 Beaches-East York English 18.9 43.681470 -79.306021
1 Davenport Portuguese 22.7 43.671561 -79.448293
2 Eglinton-Lawrence Polish 12.0 43.719265 -79.429765
我试过几种方法来合并它们,但都没有用。你知道吗
这将为所有lat和long行返回一个NaN
df3 = pd.merge(df1, df2, on="location", how="left")
返回所有民族和百分比行的NaN
df3 = pd.merge(df1, df2, on="location", how="right")
正如其他人所指出的,问题是“location”列不共享任何值。一种解决方案是使用正则表达式除去从第一个逗号开始并延伸到字符串结尾的所有内容:
使用您提供的确切数据,这仍然不起作用,因为两个数据框中有不同类型的破折号。您可以用类似的方法解决这个问题(这次不需要正则表达式):
然后按照你的建议合并
我猜您遇到的问题是,您尝试合并的列不相同,即在
df2.location
中找不到相应的值来合并到df1
。试着先改变这些,它应该会起作用:我们应该使用
findall
创建键相关问题 更多 >
编程相关推荐