【问题标题】:Find row number in column where it matches any other value in column of other dataframe在与其他数据框列中的任何其他值匹配的列中查找行号
【发布时间】:2020-06-16 03:32:37
【问题描述】:

我有一个代码:

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的内容是:

[(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'] 中的任何值相同。怎么做?

ahk_ids_new 的预期输出(内容):

Out[57]: [0, 3, 2, 9]

如果有更好的方法来使用我的代码中的数据框做我需要的事情,请发布你更好的变体,而不是修复我的代码。

【问题讨论】:

  • 请发布您的预期输出,以便我们更轻松地为您提供帮助
  • @JuanC 谢谢。完成。
  • @jfaccioni 应该是[0, 3, 2, 9]。抱歉,我来自 R,索引从 1 开始。

标签: python python-3.x pandas


【解决方案1】:

尝试isin 并在索引上切片

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]

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多