用一些逻辑为pandas datafram创建新列

2024-09-30 14:33:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要添加一个基于外部表vprices的新列“price”。在

我试着像示例中那样添加它,但是遇到了一个错误,因为括号中的df[“vol type”]是一个序列变量,而不是serie的第n个值,这正是我需要的。在

如何重写它以使用每行的值填充新列“real_size”?在

virtsizes = {
  "type1": { "gb": 1.2, "xxx": 0, "yyy": 30 },
  "type2": { "gb": 1.5, "xxx": 2, "yyy": 20  },
  "type3": { "gb": 2.3, "xxx": 0.1, "yyy": 10  },
}
df = pd.read_csv(StringIO(src),names=["vol-id","size","vol-type"])

df["real_size"] = df["size"] * ( virtsizes[df["vol-type"]]["gb"] 

谢谢!在


Tags: 示例dfsizetype错误序列realprice
2条回答

loc选择的df1行使用^{}

virtsizes = {
  "type1": { "gb": 1.2, "xxx": 0, "yyy": 30 },
  "type2": { "gb": 1.5, "xxx": 2, "yyy": 20  },
  "type3": { "gb": 2.3, "xxx": 0.1, "yyy": 10  },
}
df1 = pd.DataFrame(virtsizes)
print (df1)
     type1  type2  type3
gb     1.2    1.5    2.3
xxx    0.0    2.0    0.1
yyy   30.0   20.0   10.0

df = pd.DataFrame({'vol-type':['type1','type2']})

df["real_size"] = df["vol-type"].map(df1.loc['gb'])
print (df)
  vol-type  real_size
0    type1        1.2
1    type2        1.5

另一种解决方案是在dict comprehension中提取gb

^{pr2}$

虽不如耶斯列一世圣洁,但这也行得通:

real_size = []
for index, row in df.iterrows():
  real_size.append(row["size"] * virtsizes[["vol-type"]]["gb"])
df["real_size"] = real_size

相关问题 更多 >