Python 我想根据其他数据帧中的匹配值填充数据帧中的值
我正在编辑这个问题。我不想使用groupby来使用组值。 如果有人能通过以下方式帮助查询转换数据,我将不胜感激: 我有一个数据框,如下所示:Python 我想根据其他数据帧中的匹配值填充数据帧中的值,python,pandas,if-statement,Python,Pandas,If Statement,我正在编辑这个问题。我不想使用groupby来使用组值。 如果有人能通过以下方式帮助查询转换数据,我将不胜感激: 我有一个数据框,如下所示: df1: col1 col2 ------------ VG 12 G 11 A 10 P 06 VP 0 我想要新的数据帧,例如: df2: VG G A P VP --------------------- 12 11 10 06 0
df1:
col1 col2
------------
VG 12
G 11
A 10
P 06
VP 0
我想要新的数据帧,例如:
df2:
VG G A P VP
---------------------
12 11 10 06 0
我尝试使用if条件实现此目标,但出现以下错误:
代码:
agg
和transform
将起作用:)
如果其他一切都失败了,那么还有很长的路要走:
s = [pd.Series(g.loc[g['col2'] != 0, 'col2'].values, name=k) \
for k, g in df.groupby('col1')]
res = pd.concat(s, axis=1, ignore_index=False).fillna(0)
print(res)
A G P VG VP
0 10 11.0 6.0 12 0.0
1 50 0.0 0.0 53 0.0
感谢@user2285236改进答案:
s = df1.groupby('col1').cumcount()
df = (df1.set_index(['col1', s])['col2']
.unstack(level=0, fill_value=0)
.rename_axis(None, 1))
print (df)
A G P VG VP
0 10 11 6 12 0
1 50 0 0 53 0
说明:
我认为“VG”只是一个例子。您可以用cumcount(
s=df1.groupby('col1').cumcount()
)来概括这一点。谢谢您的回答。我必须为操作填充到不同的数据帧。
s = [pd.Series(g.loc[g['col2'] != 0, 'col2'].values, name=k) \
for k, g in df.groupby('col1')]
res = pd.concat(s, axis=1, ignore_index=False).fillna(0)
print(res)
A G P VG VP
0 10 11.0 6.0 12 0.0
1 50 0.0 0.0 53 0.0
s = df1.groupby('col1').cumcount()
df = (df1.set_index(['col1', s])['col2']
.unstack(level=0, fill_value=0)
.rename_axis(None, 1))
print (df)
A G P VG VP
0 10 11 6 12 0
1 50 0 0 53 0