gpt4 book ai didi

python - 旋转时将两组不同的列视为单个索引和列

转载 作者:太空宇宙 更新时间:2023-11-04 07:27:07 25 4
gpt4 key购买 nike

这是我的数据框:

df = pd.DataFrame({'a': list('xyz'), 'freq_a': [1, 2, 3], 'b': list('axy'), 'freq_b': [3, 4, 5], 'c': list('bzy'), 'freq_c': [5, 6, 7]})
df
a freq_a b freq_b c freq_c
0 x 1 a 3 b 5
1 y 2 x 4 z 6
2 z 3 y 5 y 7

我想对 abc 列中的每个值进行分组,如下例中的值 x

x freq_a 1
freq_b 4
freq_c NaN

最佳答案

您可以 reshape 和旋转。从那里,只需选择您想要的变量。

res = (
df.filter(like='freq')
.melt()
.assign(label=df[['a', 'b', 'c']].values.ravel())
.pivot_table(index='label', columns='variable', values='value', aggfunc='first'))

res

variable freq_a freq_b freq_c
label
a 2.0 NaN NaN
b 3.0 NaN NaN
x 1.0 4.0 NaN
y NaN 3.0 6.0
z NaN 5.0 5.0

res.loc['x']                                                                                       

variable
freq_a 1.0
freq_b 4.0
freq_c NaN
Name: x, dtype: float64

res.loc[['x']]

variable freq_a freq_b freq_c
label
x 1.0 4.0 NaN

关于python - 旋转时将两组不同的列视为单个索引和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57118567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com