我在迭代我的数据框时遇到了一个问题。我正在做的方式需要很长时间,而且我没有那么多行(我有 30 万行)
我想做什么?
检查一个 DF (A) 是否包含另一个 DF (B) 的两列的值。您可以将其视为一个多键字段
如果为 True,获取
的一列DF.B
的索引并分配给DF.A
如果为 False,两步:
一个。将未找到的两列附加到 DF.B
将新 ID 分配给 DF.A
(我做不到)
这是我的代码,其中:
df 是
DF.A
,df_id 是DF.B
:SampleID 和 ParentID 是我有兴趣检查它们是否存在于两个数据框中的两列
Real_ID 是我要为其分配
DF.B
(df_id) id 的列
for index, row in df.iterrows():
#check if columns exist in the other dataframe
real_id = df_id[(df_id['SampleID'] == row['SampleID']) & (df_id['ParentID'] == row['ParentID'])]
if real_id.empty:
#row does not exist, append to df_id
df_id = df_id.append(row[['SampleID','ParentID']])
else:
#row exists, assign id of df_id to df
row['Real_ID'] = real_id.index
示例:
DF.A (df)
Real_ID SampleID ParentID Something AnotherThing
0 20 21 a b
1 10 11 a b
2 40 51 a b
DF.B (df_id)
SampleID ParentID
0 10 11
1 20 21
结果:
Real_ID SampleID ParentID Something AnotherThing
0 1 10 11 a b
1 0 20 21 a b
2 2 40 51 a b
SampleID ParentID
0 20 21
1 10 11
2 40 51
同样,这个解决方案非常慢。我确信有更好的方法可以做到这一点,这就是我在这里问的原因。不幸的是,这是我几个小时后得到的...
谢谢
最佳答案
你可以这样做:
数据(注意B
DF中的index):
In [276]: cols = ['SampleID', 'ParentID']
In [277]: A
Out[277]:
Real_ID SampleID ParentID Something AnotherThing
0 NaN 10 11 a b
1 NaN 20 21 a b
2 NaN 40 51 a b
In [278]: B
Out[278]:
SampleID ParentID
3 10 11
5 20 21
解决方案:
In [279]: merged = pd.merge(A[cols], B, on=cols, how='outer', indicator=True)
In [280]: merged
Out[280]:
SampleID ParentID _merge
0 10 11 both
1 20 21 both
2 40 51 left_only
In [281]: B = pd.concat([B, merged.ix[merged._merge=='left_only', cols]])
In [282]: B
Out[282]:
SampleID ParentID
3 10 11
5 20 21
2 40 51
In [285]: A['Real_ID'] = pd.merge(A[cols], B.reset_index(), on=cols)['index']
In [286]: A
Out[286]:
Real_ID SampleID ParentID Something AnotherThing
0 3 10 11 a b
1 5 20 21 a b
2 2 40 51 a b
关于python - Pandas 检查行是否存在于另一个数据框中并附加索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39582138/