我使用pandas库时很新,我还不熟悉数据帧。 我试图通过使用dataframe1中的列值将数据列添加到dataframe1,使用此值作为dataframe2的索引,并获取相应的值
我有两个数据帧:
df1 = pandas.DataFrame({'customer' : pd.Series([28, 28, 29, 30],
index=['0', '1', '3', '4']),
'store' : pd.Series([14, 14, 14, 22],
index=['0', '1', '3', '4'])})
df2 = pandas.DataFrame({'value': pd.Series([6, 7, 8],
index=[0, 1, 2]),
'store': pd.Series([14, 14, 22],
index=[0,1, 2])})
df2.groupby(['store']).agg({'Value':[sum]})
我的目标是在df1中添加一个包含'值的列。当'存储'在对应于值df2的索引中值df1
期待输出:
df3 = {'customer' : pd.Series([28., 28., 29., 30.], index=['0', '1', '3', '4']),
'store' : pd.Series([14, 14, 14, 22], index=['0', '1', '3', '4']),
'value' : pd.Series([6, 6, 6, 8], index=['0', '1', '3', '4']}
我试过了:
for index, row in df1.iterrows():
df1['Values'] = df2.loc[row['store']]
但是我得到TypeError:插入列的不兼容索引与帧索引
for index, row in df1.iterrows():
df1['Values'] = df2.loc[pd.Index(row['store'])]
但我得到一个TypeError:
Index(...) must be called with a collection of some kind, 'int' was passed
非常感谢你的帮助,我真的很挣扎
答案 0 :(得分:0)
让我们更改您的groupby语句以创建add_index(
:pictures,
"(metadata->>'Year')",
name: "index_pictures_on_metadata_year"
)
并使用CREATE INDEX "index_pictures_on_metadata_year" ON "pictures" ((metadata->>'Year'))
:
pd.Series
输出:
map
答案 1 :(得分:0)
对于我来说,在将df2聚合为唯一的store
值后,这对我有用:
df1['value'] = [int(df2[df2.store==s].value) for s in df1.store]
答案 2 :(得分:0)
你只需要:
df1.merge(df2.reset_index(), how='left', on=['store'])
输出:
customer store value
0 28 14 13
1 28 14 13
2 29 14 13
3 30 22 8