[英]How to make a column of categorised group in pandas
Given a column of “food” (apple, banana, carrot, donuts, egg,...), I want to make the “category” column that contains values which correspond to each item in “food” column.给定一列“食物”(苹果、香蕉、胡萝卜、甜甜圈、鸡蛋……),我想创建“类别”列,其中包含与“食物”列中的每个项目对应的值。
Ex.前任。 given the information below给出以下信息
import pandas as pd
fruit =['apple', 'banana', 'orange']
veg =['carrot', 'onion']
meat=['chicken', 'pork', 'beef']
food = fruit + veg + meat
df = pd.DataFrame(food, columns=['food'])
df
When I write the code like this:当我编写这样的代码时:
df[df['food']=='apple']['category']='fruit'
df[df['food']=='carrot']['category']='vegetable'
However, a SettingWithCopyWarning
occurs when I write down in this way.但是,当我以这种方式写下来时,会发生SettingWithCopyWarning
。
What would be the best way to set this value?设置此值的最佳方法是什么?
You probably got a SettingWithCopy warning from pandas.您可能收到来自 pandas 的SettingWithCopy警告。 You can resolve that in a few different ways:您可以通过几种不同的方式解决该问题:
# Use loc
df['category'] = None # Initialize an empty column
df.loc[df['food']=='apple', 'category'] = 'fruit'
df.loc[df['food']=='carrot', 'category'] = 'vegetable'
# Use map
df['category'] = df['food'].map({
'apple': 'fruit',
'carrot': 'vegetable'
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.