【问题标题】:Create Pandas Column from Dictionary of Lists从列表字典创建 Pandas 列
【发布时间】:2018-02-10 18:40:13
【问题描述】:

我到处寻找,但我没有完全得到我正在寻找的答案。我正在使用更大的数据集,但我已将其分解为更简单的表示。

我正在寻找最有效的方法来创建一个 pandas 列,该列映射一个字典,其中键具有列表作为值。当字典有一个键和一个值时,下面的代码表现得非常好。但是,当我将值更改为列表时,它会引发错误。

df=pd.DataFrame({'col1': ['Dog','Dog',"Cat","John","Steve", 'Steve']})


dic={"Person":['John', 'Steve'], 
     "Animal":["Dog", "Cat"]
}


for i, v in dic.items():
    df.loc[df.col1==i, "new_col"]=v 

ValueError: Must have equal len keys and value when setting with an iterable

期望的输出:

    col1   new_col
0   Dog     Animal
1   Dog     Animal
2   Cat     Animal
3   John    Person
4   Steve   Person
5   Steve   Person

可以肯定的是,我过去一直使用 np.where 来执行此操作。我没有使用字典进行映射,而是使用 np.where 并写出每个映射。下面的代码执行得很好,但是随着更大的转换(数百个)它变得很麻烦。我正在寻找执行此任务的最“pythonic”方式。任何帮助是极大的赞赏。

import numpy as np
df["new_col"]=np.where((df.col1=="Dog")|\
                       (df.col1=="Cat"),
                       "Animal", 
                       "Person"
                          )

【问题讨论】:

    标签: pandas dictionary calculated-columns


    【解决方案1】:

    您可以用dictmap 中的值交换键:

    d = {k: oldk for oldk, oldv in dic.items() for k in oldv}
    print (d)
    {'John': 'Person', 'Steve': 'Person', 'Dog': 'Animal', 'Cat': 'Animal'}
    
    df['new_col'] = df['col1'].map(d)
    print (df)
        col1 new_col
    0    Dog  Animal
    1    Dog  Animal
    2    Cat  Animal
    3   John  Person
    4  Steve  Person
    5  Steve  Person
    

    【讨论】:

    • 太棒了!谢谢!
    猜你喜欢
    • 2020-07-22
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    相关资源
    最近更新 更多