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
输出为:
相关问题 更多 >
编程相关推荐