Pandas:从数据框更新交叉表

问题描述 投票:0回答:2

源数据框:

            T1  V1  T2  V2  T3  V3
4/1/2023    A1  10  A4  8   A2  1
4/2/2023    A2  5   A3  10  A1  7
4/3/2023    A3  7   A1  1   A4  9

目标数据框:

            A3  A2  A4  A1
4/1/2023    0   1   8   10
4/2/2023    10  5   0   7
4/3/2023    7   0   9   1

我通过循环实现了目标数据帧:

for idx in df1.index:
    for col in df1.columns:
        lst = list(df.loc[idx].values)
        val = (lst[lst.index(col)+1] if col in lst else 0)
        df1.loc[idx, col] = val

有没有更好的/直接的方法像

merge()
/
concat()
来完成这个而不需要循环?

python pandas loops lookup
2个回答
1
投票

您可以使用

pd.wide_to_long

out = (pd.wide_to_long(df.reset_index(names='Date'), ['T', 'V'], i='Date', j='var')
         .droplevel('var').set_index('T', append=True)['V']
         .unstack('T', fill_value=0).rename_axis(index=None, columns=None))

或使用

pd.concat

out = (pd.concat([pd.DataFrame(d.values, index=d.index, columns=['T', 'V']) 
                  for _, d in df.groupby(df.columns.str[1:], axis=1)])
         .set_index('T', append=True)['V'].unstack('T', fill_value=0)
         .rename_axis(columns=None))

输出:

          A1  A2  A3  A4
4/1/2023  10   1   0   8
4/2/2023   7   5  10   0
4/3/2023   1   0   7   9

0
投票

可以使用pd.crosstab函数

pd.crosstab(index=yy.index,columns=yy.T1).rename_axis(None, axis=1).rename_axis(None)
© www.soinside.com 2019 - 2024. All rights reserved.