【问题标题】:How to select values from one column in function of the values of multiple other columns如何根据多个其他列的值从一列中选择值
【发布时间】:2022-01-23 02:54:45
【问题描述】:

这是原始数据:

     Name       Wine      Year
0    Mark     Volnay      1983
1    Mark     Volnay      1979
3    Mary     Volnay      1979
4    Mary     Volnay      1999
5    Mary  Champagne      1993
6    Mary  Champagne      1989

我希望能够根据NameWine 的值获得Year 的值。它将返回在NameWine 列中具有相应值的条目的Year 列中的所有值。

例如:使用键 ['Mark', 'Volnay'] 我会得到值 [1983, 1979]

我尝试操纵数据,这是我能得到的最好的。

为每个键保留一个实例:

     Name       Wine      Year
1    Jean     Volnay      1979
4  Pierre     Volnay      1999
6  Pierre  Champagne      1989

删除Year

     Name       Wine
1    Jean     Volnay
4  Pierre     Volnay
6  Pierre  Champagne

获取列表中的值

[['Mark', 'Volnay'], ['Mary', 'Volnay'], ['Mary', 'Champagne']]

我现在有了我需要的键,但我无法根据键的值获取原始数据框中的值。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您还可以将groupbyget_group 一起使用

    def getyear(datafrae,keys:list):
        values = df.groupby(['Name', 'Wine']).get_group(tuple(key))['Year']
        dedupvalues = [*dict.fromkeys(values).keys()] #incase of duplicates
        return dedupvalues
    

    keys = ['Mark', 'Volnay']
    print(getyear(df,keys))
    [1983, 1979]
    

    【讨论】:

      【解决方案2】:

      您可以使用set_index,然后使用loc

      key = ['Mark', 'Volnay']
      lst = df.set_index(['Name', 'Wine']).loc[key, 'Year'].tolist()
      

      输出:

      >>> lst
      [1983, 1979]
      

      【讨论】:

        猜你喜欢
        • 2020-03-07
        • 1970-01-01
        • 2022-07-06
        • 2018-09-24
        • 2021-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-30
        相关资源
        最近更新 更多