[英]Assign a new value based on other column's value
So I have a dataframe Fruit that have structure look like this所以我有一个结构看起来像这样的数据框 Fruit
Fruit Sales
Apple 1000
Pear 2000
Peach 400
Banana 200
...
I want to create a new column 'Tag' that assigns value 'Others' to the fruit with sales below rank 10 (sort by sales in descending order), for fruit above(including) rank 10, assign their fruit name to the 'Tag'.我想创建一个新列“标签”,为销售额低于 10 级的水果分配值“其他”(按销售额降序排序),对于高于(包括)10 级的水果,将其水果名称分配给“标签” '。 So it should look like this assuming Peach and Banana are below sales rank 10.
因此,假设 Peach 和 Banana 低于销售排名 10,它应该看起来像这样。
Fruit Sales Tag
Apple 1000 Apple
Pear 2000 Pear
Peach 400 Others
Banana 200 Others
...
First, I sort the Fruit dataframe first by sales volume and take the first 10 records:首先,我首先按销量对 Fruit 数据框进行排序,并取前 10 条记录:
Top_fruit = Fruit.sort_values(by='Sales',ascending = False)[:10]
Second, I create a Fruit_test dataframe with 'Tag' field added to process the loc function to find the Fruit that's not in the top 10 rank list (ie, Top_fruit) and assign 'Others' to the Tag field.其次,我创建了一个 Fruit_test 数据框,其中添加了“Tag”字段以处理 loc 函数以查找不在前 10 名排名列表中的 Fruit(即 Top_fruit),并将“Others”分配给 Tag 字段。
Fruit_test = Fruit.copy()
Fruit_test['Tag'] =Fruit['Fruit']
Fruit_test.loc[~Fruit_test['Fruit'].isin((Top_fruit)),'Tag'] = 'Others'
However, I keep getting Keyerror: Fruit.但是,我不断收到 Keyerror: Fruit。 Did I do something wrong?
我做错什么了吗?
You can do it with just one line of code:您只需一行代码即可完成:
df['Tag'] = df.apply(lambda row: row['Fruit'] if row['Sales'] > 10 else 'Other', axis=1)
Test it:测试一下:
import pandas as pd
df = pd.DataFrame(
[['Apple', 1000], ['Pear', 2000], ['Peach', 8], ['Banana', 5]],
columns=['Fruit', 'Sales'])
print(df, '\n\n------------\n')
df['Tag'] = df.apply(
lambda row: row['Fruit'] if row['Sales'] > 10 else 'Other', axis=1)
print(df)
Ouput:输出:
Fruit Sales
0 Apple 1000
1 Pear 2000
2 Peach 8
3 Banana 5
------------
Fruit Sales Tag
0 Apple 1000 Apple
1 Pear 2000 Pear
2 Peach 8 Other
3 Banana 5 Other
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.