在python中,按顺序将两个不同列表中的值赋给数据帧中的一列

2024-04-26 12:13:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在dataframe的列中有两个不同的值(animal或tool)。所以每个细胞不是动物就是工具。我有一个单独的动物名称列表和工具名称列表(有工具和动物的实际名称)。如果单元格值=animal,我希望代码遍历dataframe中列的每个单元格,并从animal列表中指定动物名称;如果单元格值为tool,则从tool列表中指定工具名称。如果数据帧看起来像:

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中,这似乎应该相当简单,但没有成功。任何帮助都将不胜感激。谢谢!你知道吗


Tags: 工具名称dataframe列表indextoolcat细胞
2条回答

您可以使用两个.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)

相关问题 更多 >