Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,按顺序将两个不同列表中的值分配给数据帧中的一列_Python_List_Iteration_Sequence_Multiple Columns - Fatal编程技术网

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

在python中,按顺序将两个不同列表中的值分配给数据帧中的一列,python,list,iteration,sequence,multiple-columns,Python,List,Iteration,Sequence,Multiple Columns,我在数据框的列中有两个不同的值(动物或工具)。所以每个细胞不是动物就是工具。我有一个单独的动物名称列表和一个工具名称列表(包含工具和动物的实际名称)。我希望我的代码遍历dataframe中列的每个单元格,如果单元格值=animal,则从animal列表中指定一个动物名称;或者,如果单元值为tool,则从工具列表中选择工具名称。我希望按顺序执行此操作,因此如果数据帧看起来像: Index Category 0 animal 1 animal 2 tool 3

我在数据框的列中有两个不同的值(动物或工具)。所以每个细胞不是动物就是工具。我有一个单独的动物名称列表和一个工具名称列表(包含工具和动物的实际名称)。我希望我的代码遍历dataframe中列的每个单元格,如果单元格值=animal,则从animal列表中指定一个动物名称;或者,如果单元值为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中,这似乎应该相当简单,但还没有成功。任何帮助都将不胜感激。谢谢

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

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

将numpy导入为np
作为pd进口熊猫
#设置
df=pd.DataFrame({“Category”:['animal','animal','tool','animal','tool'],“Output”:np.nan})
动物列表=[‘猫’、‘狗’、‘鹦鹉’、‘鸟’、‘猎豹’]
工具列表=[‘钉子’、‘铁’、‘锤子’、‘轮子’、‘螺钉’]
#解决方案
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(工具列表,df.loc[df.Category=='tool','Output'].shape)

这与指定的OP没有相同的输出。对不起,我无意误导任何人。我发烧了,所以我想得不够清楚;我总是在回答这样的问题时犯这样的错误。现在看起来不错。@Arn非常感谢你!