英文:
Hitting "ValueError: The truth value of a Series is ambiguous" despite using '&'
问题
I am trying to replace values in a column based on two filter conditions. Despite using &
, I am getting the following error:
> "ValueError: The truth value of a Series is ambiguous".
This is what I have tried:
df = db.pd.DataFrame({"Fruits":["Apple","Apple","Apple","Orange","Orange","Orange"],\
"Year": [2010,2011,2012,2010,2011,2012], \
"Price": [2,3,1,1,2,3]})
df["Change"] = ""
df["Change"] = df.apply(lambda x: "Increase" if (x['Price'] < df.loc[(df["Year"]+1 == x['Year'])\
& (df['Fruits'] == x['Fruits'])]['Price']) else '', axis = 1)
英文:
I am trying to replace values in a column based on two filter conditions. Despite using &
, I am getting the following error:
> "ValueError: The truth value of a Series is ambiguous".
This is what I have tried:
df = db.pd.DataFrame({"Fruits":["Apple","Apple","Apple","Orange","Orange","Orange"],\
"Year": [2010,2011,2012,2010,2011,2012], \
"Price": [2,3,1,1,2,3]})
df["Change"] = ""
df["Change"] = df.apply(lambda x: "Increase" if (x['Price'] < df.loc[(df["Year"]+1 == x['Year'])\
& (df['Fruits'] == x['Fruits'])]['Price']) else '', axis = 1)
答案1
得分: 0
你需要使用 .any()
,它会在可迭代对象中的任何元素为真时返回 True
,否则返回 False
。所以,在你的情况下,它将识别所有满足条件的实例,并将值赋给列 Change
为 Increase
。
请改用以下方式:
import pandas as pd
df = pd.DataFrame({"Fruits":["Apple","Apple","Apple","Orange","Orange","Orange"],
"Year": [2010,2011,2012,2010,2011,2012],
"Price": [2,3,1,1,2,3]})
df["Change"] = df.apply(lambda x: "Increase" if ((df["Year"] == x["Year"]-1) & (df["Fruits"] == x["Fruits"]) & (df["Price"] < x["Price"])).any() else "", axis=1)
print(df)
这将产生以下结果:
Fruits Year Price Change
0 Apple 2010 2
1 Apple 2011 3 Increase
2 Apple 2012 1
3 Orange 2010 1
4 Orange 2011 2 Increase
5 Orange 2012 3 Increase
英文:
You need to use .any()
which returns True
if any item in an iterable are true, otherwise it returns False. So, in your case it will identify all instances for which your conditions are True
and assign Increase
to the value of the column Change
.
Do this instead:
import pandas as pd
df = pd.DataFrame({"Fruits":["Apple","Apple","Apple","Orange","Orange","Orange"],\
"Year": [2010,2011,2012,2010,2011,2012], \
"Price": [2,3,1,1,2,3]})
df["Change"] = df.apply(lambda x: "Increase" if ((df["Year"] == x["Year"]-1) & (df["Fruits"] == x["Fruits"]) & (df["Price"] < x["Price"])).any() else "", axis=1)
print(df)
which gives
Fruits Year Price Change
0 Apple 2010 2
1 Apple 2011 3 Increase
2 Apple 2012 1
3 Orange 2010 1
4 Orange 2011 2 Increase
5 Orange 2012 3 Increase
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论