![](/img/trans.png)
[英]How to split a pandas dataframe of different column sizes into separate dataframes?
[英]How to merge pandas dataframes with different row and column sizes?
我想根据dataframe2中的'Race'合并dataframe 1和dataframe 2。 我只想包括 dataframe 2 的“比赛”,不想包括 dataframe 1 中多余的“比赛”。
我的代码:
cols1 = ['Race', 'Market ID']
df1 = pd.DataFrame(data=betfairevents, columns=cols1)
cols2 = ['Race']
df2 = pd.DataFrame(data=tabntgevents, columns=cols2)
print(df2)
dfmerge1 = pd.merge(df1,df2,on='Race',how='inner')
数据帧1的Output:
Race Market ID
0 Newcastle R1 1.171771969
1 Newcastle R2 1.171771971
2 Newcastle R3 1.171771973
3 Newcastle R4 1.171771975
4 Newcastle R5 1.171771977
.. ... ...
139 Launceston R6 1.171772509
140 Launceston R7 1.171772511
141 Launceston R8 1.171772513
142 Launceston R9 1.171772515
143 Launceston R10 1.171772517
数据帧2的Output:
Race
0 NEWCASTLE R1
1 BALLARAT R1
2 LISMORE R4
3 WARRAGUL R3
合并 Z6A8064B5DF4794555500553C47C55057DZ 的所需 output:
Race Market ID
0 Newcastle R1 1.171771969
1 Ballarat R1 1.171771971
2 Lismore R4 1.171771973
3 Warragul R3 1.171771975
您可以使用 pandas 中的“.isin” function,
merged_df = df1[df1['Race'].isin(df2['Race'])
您显示的示例输入数据与所需的 output 不匹配。 但这是执行分析的一种方法:
# create sample data
from io import StringIO
import pandas as pd
data1 = '''index Race Market ID
0 Newcastle R1 1.171771969
1 Newcastle R2 1.171771971
2 Newcastle R3 1.171771973
3 Newcastle R4 1.171771975
4 Newcastle R5 1.171771977
139 Launceston R6 1.171772509
140 Launceston R7 1.171772511
141 Launceston R8 1.171772513
142 Launceston R9 1.171772515
143 Launceston R10 1.171772517
'''
df1 = pd.read_csv(StringIO(data1), sep='\s\s+', engine='python').set_index('index')
data2 = '''index Race
0 NEWCASTLE R1
1 BALLARAT R1
2 LISMORE R4
3 WARRAGUL R3
'''
df2 = pd.read_csv(StringIO(data2), sep='\s\s+', engine='python').set_index('index')
现在找到 df1 和 df2 中的“种族”值(使用 boolean 掩码)。 .str().lower()
执行不区分大小写的比较。
mask = df1['Race'].str.lower().isin(df2['Race'].str.lower().values)
df1[ mask ]
merge()
function 也适用于此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.