【问题标题】:convert text/string to number/int for python dataframe [duplicate]将文本/字符串转换为python数据框的数字/整数[重复]
【发布时间】:2020-04-01 13:15:30
【问题描述】:

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

【问题讨论】:

  • 嗨 Sirimiri - 见link。它应该回答你的问题。
  • 使用df['Number'] = pd.factorize(df.Fruit)[0] + 1

标签: python pandas dataframe type-conversion


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 2019-11-08
    • 2013-10-06
    • 2022-08-05
    • 2022-12-19
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    相关资源
    最近更新 更多