【发布时间】:2017-11-14 15:04:00
【问题描述】:
我已经搜索了我的确切问题,但无济于事。这两个线程Creating a new column based on if-elif-else condition 和 create new pandas dataframe column based on if-else condition with a lookup 引导我的代码,尽管我的代码无法执行。
问题:我有一个数据框,我在下面复制了示例。区域属性只有两个值 - a 或 b(或可能有更多),年份相同,但区域 a 可能有两个年份等。我想要做的是创建一个新列“美元”,并查找值对于地区,如果是地区“a”并且年份是例如 2006 年,则在该行中获取销售额,然后乘以 该年的汇率,并在新列中附加值 - 美元。我是初学者,下面是我到目前为止所拥有的 - 通过函数 - 显然执行 .apply 函数会返回一个 ValueError: ('一个系列的真值是不明确的。使用 a.empty, a .bool()、a.item()、a.any() 或 a.all().', '发生在索引 0')。我对更高效的实现特别感兴趣,因为数据框相当大,并且希望优化计算效率。
import pandas as np
rate_2006, rate_2007 = 100, 200
c = {
'region': ["a", "a", "a", "a", "a", "b", "b", "b", "b", "a", "b"],
'year': [2006, 2007, 2007, 2006, 2006, 2006, 2007, 2007, 2007, 2006, 2007],
'sales': [500, 100, 2990, 15, 5000, 2000, 150, 300, 250, 1005, 600]
}
df1 = pd.DataFrame(c)
df1
def new_col(row):
if df1["region"] == "a" and df1["year"] == 2006:
nc = row["sales"] * rate_2006
elif df1["region"] == "a" and df1["year"] == 2007:
nc = row["sales"] * rate_2007
elif df1["region"] == "b" and df1["year"] == 2006:
nc = row["sales"] * rate_2006
else:
nc = row["sales"] * rate_2007
return nc
df1["Dollars"] = df1.apply(new_col, axis=1)
df1
【问题讨论】: