【问题标题】:Cross reference columns within the same dataframe Pandas Python同一数据框 Pandas Python 中的交叉引用列
【发布时间】:2021-01-27 23:29:26
【问题描述】:

** 我已将两列的示例 df 编辑为元组而不是整数,以说明将数据从整数更改为元组后解决方案遇到的问题**

我正在尝试在 Pandas 中创建一个新列,其值将取决于特定列的值出现在单独列的不同行上,并且在找到匹配项的情况下,使用第三列的值。

为了说明,请参见下面的示例。

我在 df.apply() 中使用 lambda 函数来执行以下操作:在第一行中,它将过滤“二”列的值等于“零”列的值的行,以及它在哪里确实,它获取列“一”的值并将其复制到新列“三”中。

df = pd.DataFrame([[(0,9),(1,9),(2,9),(3,9),(4,9)],['a','b' ,'c','d','e'],[(2,9),(3,9),(4,9),(5,9),(6,9)]]).transpose( )

df.columns = ['zero','one','two']

df['three] = df.apply(lambda x : df[df['zero'] == x['two']].loc[:,'one'], axis=1)

注意,“二”列和“零”列是唯一的,因此过滤结果将永远只有一行。

理论上,“三”列的结果应该是:“c”、“d”、“e”、“nan”、“nan”。

谢谢

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    只需将行zero设置为索引,方便查找列one

    更新:该解决方案现在适用于元组索引。

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame([[0,1,2,3,4],['a','b','c','d','e'],[2,3,4,5,6]]).transpose()
    df.columns = ['zero','one','two']
    
    # set index for quick lookup    
    df_indexed = df.set_index("zero")
    
    # the indexed dataset look like this
    df_indexed
    Out[21]: 
         one two
    zero        
    0      a   2
    1      b   3
    2      c   4
    3      d   5
    4      e   6
    
    # apply the mapping logic, taking df_indexed from outside the function
    def f(el):
        return df_indexed.at[el, "one"] if el in df_indexed.index else np.nan
    
    df["three"] = df["two"].apply(f)
    
    print(df)
    Out[18]: 
      zero one two three
    0    0   a   2     c
    1    1   b   3     d
    2    2   c   4     e
    3    3   d   5   NaN
    4    4   e   6   NaN
    
    # On the updated dataset
    df
    Out[71]: 
         zero one     two three
    0  (0, 9)   a  (2, 9)     c
    1  (1, 9)   b  (3, 9)     d
    2  (2, 9)   c  (4, 9)     e
    3  (3, 9)   d  (5, 9)   NaN
    4  (4, 9)   e  (6, 9)   NaN
    

    【讨论】:

    • 比尔,你的回答在这里完美。有一件事是,我的实际索引是一个元组,出于某种原因,这被抛弃了。我认为这与el<class 'tuple'> 有关,而df_index.index 项目,当我通过type(df_indexed.index[0]) 检查时只会导致“元组”。 keyerror 看起来像这样:KeyError: "None of [Index([(1, 1), (2, 1), (3, 1)], dtype='object', name='tenors')] are in the [index]" 这让我觉得我需要访问el 的值?
    • 我无法理解。对我来说,问题只与第 0 列、第 1 列和第 2 列有关,而与索引无关,无论索引包含什么。你可以举例说明吗?仅供参考,您可以在 .set_index() 之前 .reset_index() 以允许重新分配索引列而不会丢失数据。
    • 我已将上面的示例 df 编辑为第 0 列和第 2 列中的元组,这似乎使解决方案无法解决...
    • 我终于明白了。应该使用.at[] 而不是.loc[],因为无论索引是什么,都期望返回一个值。忽略这一点确实是我的坏事。该解决方案现在应该适用于元组索引。:)
    • 好的,这很棒。完美运行。非常感谢您的帮助。
    猜你喜欢
    • 2021-10-12
    • 2014-10-31
    • 2015-10-26
    • 1970-01-01
    • 2017-05-22
    • 2018-11-12
    • 2020-07-24
    • 1970-01-01
    相关资源
    最近更新 更多