[英]Create new column with some logic to pandas dataframe
我需要根据外部表 vprices 添加一个新列“价格”。
我尝试在示例中添加它,但出现错误,因为在括号 df["vol-type"] 内是一个系列变量,而不是系列的第 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"]
谢谢!
按loc
选择的df1
行使用map
:
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
:
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 },
}
d = {k:v['gb'] for k,v in virtsizes.items()}
print (d)
{'type2': 1.5, 'type1': 1.2, 'type3': 2.3}
df = pd.DataFrame({'vol-type':['type1','type2']})
df["real_size"] = df["vol-type"].map(d)
print (df)
vol-type real_size
0 type1 1.2
1 type2 1.5
不像 jezrael 那样好,但这也有效:
real_size = []
for index, row in df.iterrows():
real_size.append(row["size"] * virtsizes[["vol-type"]]["gb"])
df["real_size"] = real_size
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.