Python 大熊猫的条件反射
我尝试获取pandas数据帧,并在根据某些条件添加值为small-medium或large的新列“Size\u Category”后返回pandas数据帧对象Python 大熊猫的条件反射,python,pandas,Python,Pandas,我尝试获取pandas数据帧,并在根据某些条件添加值为small-medium或large的新列“Size\u Category”后返回pandas数据帧对象 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['
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
mod_df=df.copy(deep=True)
mod_df.loc[(mod_df['Length']=450,'Size_Category')]=“large”#条件,新列
当我这样做的时候,它给了我一个错误的说法
级数的真值是模糊的。使用a.empty、a.bool()、a.item()、a.any()或a.all()
我如何处理这个问题?您缺少()
:
如果我的回答有帮助,不要忘记接受它。谢谢
mod_df.loc[(mod_df['Length'] <= 300) | (mod_df['Length'] > 450) , 'Size_Category')]
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