Skip to main content
 首页 » 编程设计

python之Pandas 的调理

2024年10月01日8wayfarer

在添加新列“Size_Category”后,我尝试获取一个 pandas 数据框并返回一个 pandas 数据框对象,该列的值根据某些条件为 small medium 或 large。

mod_df = df.copy(deep=True) 
mod_df.loc[(mod_df['Length'] <= 300 , 'Size_Category')] = 'small' # condition, new_column 
mod_df.loc[(mod_df['Length'] <= 300 | mod_df['Length'] > 450) , 'Size_Category')] = 'medium' # condition, new_column 
mod_df.loc[(mod_df['Length'] >= 450, 'Size_Category')] = 'large' # condition, new_column 

当我这样做的时候,它给我一个错误提示

Series 的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我该如何处理?

请您参考如下方法:

您缺少 ():

mod_df.loc[(mod_df['Length'] <= 300) | (mod_df['Length'] > 450) , 'Size_Category')] 

另一个解决方案是使用 cut :

df = pd.DataFrame({'Length': [0,10,300,400,449,450,500]}) 
 
bins = [-np.inf, 300, 449, np.inf] 
labels=['small','medium','large'] 
df['Size_Category'] = pd.cut(df['Length'], bins=bins, labels=labels) 
print (df) 
   Length Size_Category 
0       0         small 
1      10         small 
2     300         small 
3     400        medium 
4     449        medium 
5     450         large 
6     500         large