[英]pandas dataframe: make new dataframe from lookup and computation of existing dataframes
Im trying to use data from two dateframes to create a new dataframe 我正在尝试使用来自两个日期框架的数据来创建一个新的数据框架
lookup_data = [
{ 'item': 'apple',
'attribute_1':3,
'attribute_2':2,
'attribute_3':10,
'attribute_4':0,
},
{ 'item': 'orange',
'attribute_1':0.4,
'attribute_2':20,
'attribute_3':1,
'attribute_4':9,
},
{ 'item': 'pear',
'attribute_1':0,
'attribute_2':0,
'attribute_3':30,
'attribute_4':0,
},
{ 'item': 'peach',
'attribute_1':2,
'attribute_2':2,
'attribute_3':3,
'attribute_4':6,
},]
df_lookup_data = pd.DataFrame(lookup_data,dtype=float)
df_lookup_data.set_index('item', inplace=True, drop=True)
collected_data = [
{ 'item':'apple',
'qnt': 4},
{ 'item':'orange',
'qnt': 2},
{ 'item':'pear',
'qnt': 7},
]
df_collected_data = pd.DataFrame(collected_data,dtype=float)
df_collected_data.set_index('item', inplace=True, drop=True)
df_result = pd.DataFrame(
.... first column is item type
.... second column is qnt*attribute_1
.... second column is qnt*attribute_2
.... second column is qnt*attribute_3
.... second column is qnt*attribute_4
)
df_result.columns = ['item', 'attribute_1', 'attribute_2', 'attribute_3', 'attribute_4']
print(result)
the result should print 结果应该打印
item attribute_1 attribute_2 attribute_3 attribute_4
0 apple 14 8 40 0
1 orange 0.8 40 2 18
2 pear 0 0 210 0
but im really not sure how i get date from these two dataframes and make this new one 但我真的不确定我如何从这两个数据框中获取日期并制作新的
No need to merge
or concat
here. 无需merge
或concat
位置。 Since indexes do match, simply mul
across axis=0
由于索引确实匹配,因此只需跨axis=0
mul
axis=0
>>> df_lookup_data.mul(df_collected_data.qnt, axis=0)
attribute_1 attribute_2 attribute_3 attribute_4
item
apple 12.0 8.0 40.0 0.0
orange 0.8 40.0 2.0 18.0
peach NaN NaN NaN NaN
pear 0.0 0.0 210.0 0.0
Or use: 或使用:
df_lookup_data = pd.DataFrame(lookup_data,dtype=float)
items = [i['item'] for i in collected_data]
qnts = [i['qnt'] for i in collected_data]
print(df_lookup_data[df_lookup_data['item'].isin(items)].set_index('item').mul(qnts, axis=0))
Output: 输出:
attribute_1 attribute_2 attribute_3 attribute_4
item
apple 12.0 8.0 40.0 0.0
orange 0.8 40.0 2.0 18.0
pear 0.0 0.0 210.0 0.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.