从列表词典创建 Pandas 列
Create Pandas Column from Dictionary of Lists
我到处都找过了,但我并没有得到我正在寻找的答案。我正在处理一个更大的数据集,但我已将其分解为更简单的表示形式。
我正在寻找创建 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"
)
您可以将键与 dict
中的值交换,然后 map
:
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
我到处都找过了,但我并没有得到我正在寻找的答案。我正在处理一个更大的数据集,但我已将其分解为更简单的表示形式。
我正在寻找创建 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"
)
您可以将键与 dict
中的值交换,然后 map
:
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