我有一个很长很宽的数据框。我想在该数据框中创建一个新列,其中的值取决于 df 中的许多其他列。此新列中的值所需的计算也会更改,具体取决于其他列中的值。
this question 的答案和 this question接近,但不太适合我。
我最终会有大约 30 种不同的计算可以应用,所以我不太喜欢 np.where 函数,它在太多条件下不是那么可读。
我也被强烈建议不要对数据框中的所有行进行 for 循环,因为这对性能来说应该很糟糕(如果我错了请纠正我)。
我尝试做的是:
import pandas as pd
import numpy as np
# Information in my columns look something like this:
df['text'] = ['dab', 'def', 'bla', 'zdag', 'etc']
df['values1'] = [3 , 4, 2, 5, 2]
df['values2'] = [6, 3, 21, 44, 22]
df['values3'] = [103, 444, 33, 425, 200]
# lists to check against to decide upon which calculation is required
someList = ['dab', 'bla']
someOtherList = ['def', 'zdag']
someThirdList = ['etc']
conditions = [
(df['text'] is None),
(df['text'] in someList),
(df['text'] in someOtherList),
(df['text'] in someThirdList)]
choices = [0,
round(df['values2'] * 0.5 * df['values3'], 2),
df['values1'] + df['values2'] - df['values3'],
df['values1'] + 249]
df['mynewvalue'] = np.select(conditions, choices, default=0)
print(df)
我希望根据 df['text'] 中的行值,将正确的计算应用于 df['mynewvalue'] 的同一行值.
相反,我收到错误 The truth value of a Series is ambiguous。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
我该如何对此进行编程,以便我可以使用这些条件来为该 df['mynewvalue'] 列定义正确的计算?
请您参考如下方法:
错误来自以下条件:
conditions = [
... ,
(df['text'] in someList),
(df['text'] in someOtherList),
(df['text'] in someThirdList)]
您尝试询问列表中是否有多个元素。答案是一个列表(针对每个元素)。正如错误提示的那样,您必须在至少一个元素验证属性(any)或所有元素都验证属性(any)时决定是否验证条件.
一个解决方案是使用isin (doc)或全部 (doc)对于 pandas 数据帧。
此处使用any:
import pandas as pd
import numpy as np
# Information in my columns look something like this:
df = pd.DataFrame()
df['text'] = ['dab', 'def', 'bla', 'zdag', 'etc']
df['values1'] = [3, 4, 2, 5, 2]
df['values2'] = [6, 3, 21, 44, 22]
df['values3'] = [103, 444, 33, 425, 200]
# other lists to test against whether
someList = ['dab', 'bla']
someOtherList = ['def', 'zdag']
someThirdList = ['etc']
conditions = [
(df['text'] is None),
(df['text'].isin(someList)),
(df['text'].isin(someOtherList)),
(df['text'].isin(someThirdList))]
choices = [0,
round(df['values2'] * 0.5 * df['values3'], 2),
df['values1'] + df['values2'] - df['values3'],
df['values1'] + 249]
df['mynewvalue'] = np.select(conditions, choices, default=0)
print(df)
# text values1 values2 values3 mynewvalue
# 0 dab 3 6 103 309.0
# 1 def 4 3 444 -437.0
# 2 bla 2 21 33 346.5
# 3 zdag 5 44 425 -376.0
# 4 etc 2 22 200 251.0
