在列中查找与其他数据框列中的任何其他值匹配的行号 [英] Find row number in column where it matches any other value in column of other dataframe
问题描述
我有一个代码:
import pandas as pd
import numpy as np
arm_1_and_m1_df = pd.DataFrame({ 'record_id': [1, 4, 3, np.nan],
'two': [1, 2, np.nan , 4]
})
redcap_final_arm1_data = pd.DataFrame({ 'record_id': [1, 2, 3, 4, 5, 6, 7, 8, 9, np.nan],
'two': [1, 2, 3, 4, 5, 6, 7, 8, 9, np.nan]
})
ahk_ids_new=[]
for items in arm_1_and_m1_df['record_id'].iteritems(): # https://www.geeksforgeeks.org/python-pandas-series-iteritems/
ahk_ids_new.append(np.where(redcap_final_arm1_data['record_id'] == items)) # https://stackoverflow.com/questions/48519062/rs-which-and-which-min-equivalent-in-python
运行上面的代码和ahk_ids_new
之后ahk_ids_new
的内容是:
After running code above and after ahk_ids_new
the content of ahk_ids_new
is:
[(array([], dtype=int64),),
(array([], dtype=int64),),
(array([], dtype=int64),),
(array([], dtype=int64),)]
redcap_final_arm1_data['record_id']
中的值是唯一的.
问题:我想获取 ahk_ids_new
中 redcap_final_arm1_data['record_id']
的所有行号(索引),其中 redcap_final_arm1_data['record_id']
与 arm_1_and_m1_df['record_id']
中的任何值具有相同的值.怎么做?
Question: I want to get all row numbers (index) of redcap_final_arm1_data['record_id']
in ahk_ids_new
where redcap_final_arm1_data['record_id']
has the same value as any values in arm_1_and_m1_df['record_id']
. How to do that?
ahk_ids_new
的预期输出(内容):
Expected output (content) of ahk_ids_new
:
Out[57]: [0, 3, 2, 9]
如果有更好的方法来处理我的代码中的数据框,请发布您更好的变体,而不是修复我的代码.
推荐答案
尝试 isin
并在索引上切片
Try isin
and slicing on index
a_index = (redcap_final_arm1_data.index[redcap_final_arm1_data.record_id
.isin(arm_1_and_m1_df.record_id)].tolist())
输出:
Out[1355]: [0, 2, 3, 9]
这篇关于在列中查找与其他数据框列中的任何其他值匹配的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!