首页 > 解决方案 > Python pandas数据框,如何获取设置的数字

问题描述

这是示例:

df=pd.DataFrame([('apple'),('apple'),('apple'),('orange'),('orange')],columns=['A'])

df
Out[5]: 
        A
0   apple
1   apple
2   apple
3  orange
4  orange

我想在它旁边分配一个数字,例如,apple 是第一组列表 ['apple','orange'],B 列是 1,然后是 2 为橙色:

        A   B
0   apple   1
1   apple   1
2   apple   1
3  orange   2
4  orange   2

贝娄行不通。

df['B']=df['A'].tolist().index(df['A']) +1 

标签: pandasdataframe

解决方案


您可以使用该pd.factorize功能。此函数用于将数组转换为分类数组。

pd.Series.factorize也可以作为pd.Series对象的方法使用:

codes, _ = df["A"].factorize()
df["B"] = codes + 1

print(df)
        A  B
0   apple  1
1   apple  1
2   apple  1
3  orange  2
4  orange  2

推荐阅读