将python datafram的text/string转换为number/int

2024-09-21 01:18:02 发布

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

我可以知道如何将文本/字符串数据转换为数据框中某列的数字吗? 如果相同的文本/字符串再次出现,它们应该返回相同的数字。 寻找一个通用的方法来转换,因为世界上有成千上万的水果 示例:
果实数(预期结果)
1苹果1
2橙色2
3苹果1
4香蕉3
5个黑莓4
6鳄梨5
7葡萄6
8橙色2
9苹果1
10芒果7
. . . . . . . . . 你知道吗


Tags: 数据方法字符串文本苹果示例世界数字
1条回答
网友
1楼 · 发布于 2024-09-21 01:18:02
import pandas as pd 

fruitList={'name':[ "Apple","Orange","Apple","Banana","Blackberries","Avocado","Grapes","Orange","Apple","Mango"] }
df = pd.DataFrame(fruitList) 

# get distinct fruit names
unique=df.name.unique()
# generating a dictionary based on Id of unique fruit names using list comprehension
dict={ x:index+1 for index, x in enumerate(unique) }
# assigning new column 'Id' values from the dictionary using the map function 
df['Id']  = df["name"].map(dict)
print(df)

输出为:

        name      Id
0         Apple   1
1        Orange   2
2         Apple   1
3        Banana   3
4  Blackberries   4
5       Avocado   5
6        Grapes   6
7        Orange   2
8         Apple   1
9         Mango   7

相关问题 更多 >

    热门问题