[英]Using df.loc[] and In
I am trying to do the following code : 我正在尝试执行以下代码:
df.loc[df['Column'] in list]=1
df.loc[df['Column'] not in list]=2
But I have the famous error 但是我有个著名的错误
The truth value of a Series is ambiguous.
系列的真实值是不明确的。 Use a.empty, a.bool(), a.item(), a.any() or a.all().
使用a.empty,a.bool(),a.item(),a.any()或a.all()。
So from what I understood from this error I already got, it is linked with the logic. 因此,从我对这个错误的理解中可以发现,它与逻辑联系在一起。 What I want to know is Is there a specific typo to do what I am trying to do with a list, or do I have to expand my entire list like that (which in my case would be pretty ugly and long) :
我想知道的是,是否有特定的错字来做我要对列表执行的操作,还是我必须像这样扩展我的整个列表(在我的情况下这会很丑陋且很长):
df.loc[df[('Column']=='a') & (df['Column']=='b')]=1
df.loc[df[('Column']!='a') & (df['Column']!='b')]=2
I'd use np.where
. 我会使用
np.where
。 However, you need a column name. 但是,您需要一个列名。
df['new_column'] = np.where(df['Column'].isin(lst), 1, 2)
Consider the list lst
and dataframe df
考虑列表
lst
和dataframe df
lst = [1, 2, 3]
df = pd.DataFrame(dict(Column=[0, 1, 2, 3, 4]))
Then 然后
df['new_column'] = np.where(df['Column'].isin(lst), 1, 2)
print(df)
Column new_column
0 0 2
1 1 1
2 2 1
3 3 1
4 4 2
您正在寻找的功能是
df.loc[df['Column'].isin(list)] = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.