将来自两个不同列表的值依次分配给 python 中数据框中的列

Sequentially assign values from two different lists to a column in a dataframe in python

我在数据框的列中有两个不同的值(动物或工具)。所以每个细胞要么是动物,要么是工具。我有一个单独的动物名称列表和一个工具名称列表(具有工具和动物的实际名称)。我希望我的代码遍历数据框中列的每个单元格,并在单元格值 = 动物时从动物列表中分配一个动物名称;或工具列表中的工具名称(如果单元格值为工具)。我希望按顺序完成此操作,因此如果数据框如下所示:

Index  Category
0      animal
1      animal
2       tool
3      animal
4       tool

动物列表是:

cat
dog
parrot
bird
cheetah

工具列表是:

nail
iron
hammer
wheel
screw

输出应该是:

Index Category    Output
0      animal     cat
1      animal     dog
2       tool      nail
3      animal     parrot
4       tool      iron

这在 Python 中似乎应该相当简单,但尚未成功。任何帮助,将不胜感激。谢谢!

您可以使用两个 .loc 调用有条件地分配值。此外,我指定使用两个 .len 调用从每个列表中获取多少个值。

df.loc[df['Category'] == 'animal','Output'] = animal[:len(df[df['Category'] == 'animal'])]
df.loc[df['Category'] == 'tool','Output'] = tool[:len(df[df['Category'] == 'tool'])]

在这种情况下,由于只有两个类别,animaltool,您可以通过选择包含前者和后者的行以简单有效的方式解决此问题单独的类别值并将列表分配给它们:

import numpy as np
import pandas as pd

# setup
df = pd.DataFrame({"Category": ['animal', 'animal', 'tool', 'animal', 'tool'], "Output": np.nan})
animal_list = ['cat', 'dog', 'parrot', 'bird', 'cheetah']
tool_list = ['nail', 'iron', 'hammer', 'wheel', 'screw']

# solution
df.loc[df.Category == 'animal', 'Output'] =  np.resize(animal_list, df.loc[df.Category == 'animal', 'Output'].shape)
df.loc[df.Category == 'tool', 'Output'] =  np.resize(tool_list, df.loc[df.Category == 'tool', 'Output'].shape)