Skip to main content
 首页 » 编程设计

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

2025年05月04日12JustinYoung

这是我的数据框:

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 

我想对 a、b、c 列中的每个值进行分组,如下例中的值 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