简体   繁体   English

错误:Series 的真值不明确

[英]Error: The truth value of a Series is ambiguous

I'm trying to generate a new columns using following code我正在尝试使用以下代码生成新列

list = ['LHR','-1','-3','LGW','MAD','SIN','KUL','JFK','HKG','PVG','IST','SDA','GLA']
for i in list:
    if plotdata.loc[plotdata['LOCATION'] == i] :
        plotdata['city'] = plotdata['LOCATION']
    else:
        plotdata['city'] = 'others'

I get the following error:我收到以下错误:

ValueError: The truth value of a DataFrame is ambiguous. ValueError:DataFrame 的真值不明确。 Use a.empty, a.bool(), a.item(), a.any() or a.all().使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

The datatype is category, why do I get this error, please?数据类型是类别,请问为什么会出现此错误?

Not sure why you're getting this error.不知道你为什么会收到这个错误。 But, it's best-practice to not loop through pandas.但是,最好不要遍历 pandas。

You could avoid that error by setting the "city" to whatever the "location" is and then reverting back to "others" if it's not in the list.您可以通过将“城市”设置为“位置”的任何内容来避免该错误,然后如果它不在列表中,则恢复为“其他”。

city_list = ['LHR','-1','-3','LGW','MAD','SIN','KUL','JFK','HKG','PVG','IST','SDA','GLA']
plotdata['city'] = plotdata['LOCATION']
plotdata.loc[~plotdata['city'].isin(city_list), 'city'] = 'other'

You get this error because the following code:您收到此错误是因为以下代码:

if plotdata.loc[plotdata['LOCATION'] == i]

is testing on a subset of the dataframe plotdata returned by .loc() , which in turns is because the Boolean mask:正在测试.loc()返回的 dataframe plotdata的子集,这反过来是因为 Boolean 掩码:

plotdata['LOCATION'] == i

returns a Boolean array.返回一个 Boolean 数组。

Overall, since .loc() returns a subset of dataframe, hence the message:总的来说,由于.loc()返回 dataframe 的子集,因此消息:

ValueError: The truth value of a DataFrame is ambiguous. ValueError: DataFrame的真值不明确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM