Pandas宽到长,有树桩清单

2024-05-17 13:59:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我当前有以下数据帧:

        1_1       1_2       1_3       1_4       1_5       2_1  ...       9_5      10_1      10_2      10_3      10_4      10_5

0  0.049400  0.063812  0.097736 -0.077222  0.112779 -0.201620  ...  0.138246  0.015369 -0.083559 -0.186949  0.158505 -0.046787 
1 -0.169837  0.093606  0.043157  0.095289 -0.078525 -0.026500  ... -0.054344  0.008955  0.045036  0.198438  0.197416 -0.057831 
2 -0.192915  0.001477  0.077699  …

我想得到这样的东西:

cat     u       i       mouse       

0       1       1      0.049400 
1       1       1     -0.169837
2       1       1     -0.192915
0       1       2      0.063812
1       1       2      0.093606
2       1       2      0.001477
…

实际上,这些行表示cat列的值,下划线前面的数字表示u列,后面的数字表示i列。最后,鼠标列是前面因素组合的值。你知道吗

但是,解决方案应该适用于这种格式的任何数据。你知道吗

到目前为止,考虑到我可以访问u(在本例中是1,2,3,4,5,6,7,8,9,10)和I(1,2,3,4,5)的列表,我有这个问题,但是解决方案应该适用于不同的列表和不同的行数。你知道吗

u_seq_stub = [u + '_' for u in u_seq] 
df = pd.wide_to_long(df, u_seq_stub, i='u', j='i').reset_index().rename(columns={'_':'u'})

但是,这不起作用,抛出“KeyError:[Index(['userid'],dtype='object')]中没有一个在[columns]”。。。我也咨询过this,看起来和我想要的没什么区别,但肯定有什么我误解了。你知道吗

我提前感谢你的帮助。你知道吗


Tags: columns数据df列表for格式数字鼠标
2条回答

MultiIndex的所有列使用split,然后按^{}重塑,按^{}更改新列名的级别,最后按^{}将其转换为列:

df.columns = df.columns.str.split('_', expand=True)
df = df.unstack().rename_axis(('u','i','cat')).reset_index(name='mouse')
print (df.head(10))
   u  i  cat     mouse
0  1  1    0  0.049400
1  1  1    1 -0.169837
2  1  1    2 -0.192915
3  1  2    0  0.063812
4  1  2    1  0.093606
5  1  2    2  0.001477
6  1  3    0  0.097736
7  1  3    1  0.043157
8  1  3    2  0.077699
9  1  4    0 -0.077222

您的解决方案应该首先用^{}中的参数sep进行更改,然后用^{}进行另一个重塑,并进行一些数据清理:

u_seq_stub = ['1','2',...,'9','10']
#alternative
#u_seq_stub = [str(x) for x in range(1,11)]


df = (pd.wide_to_long(df.reset_index(), 
                     u_seq_stub, 
                     i='index', 
                     j='i', 
                     sep='_')
      .stack()
      .reset_index(name='mouse')
      .rename(columns={'index':'cat', 'level_2':'u'})
      .astype({'i':int, 'u':int})
      .sort_values(['u','i','cat'])
      )
print (df.head(10))
    cat  i  u     mouse
0     0  1  1  0.049400
12    1  1  1 -0.169837
24    2  1  1 -0.192915
3     0  2  1  0.063812
15    1  2  1  0.093606
25    2  2  1  0.001477
5     0  3  1  0.097736
17    1  3  1  0.043157
26    2  3  1  0.077699
7     0  4  1 -0.077222

使用^{}+^{}expand=True。要创建cat列,可以使用^{}

new_df=df.melt(var_name='u_i',value_name='mouse')
new_df['cat']=new_df.groupby('u_i').cumcount()
new_df[['u','i']]=new_df['u_i'].str.split('_',expand=True)
new_df=new_df.drop('u_i',axis=1).reindex(columns=['cat','u','i','mouse'])

print(new_df)

   cat  u  i     mouse
0    0  1  1  0.049400
1    1  1  1 -0.169837
2    2  1  1 -0.192915
3    0  1  2  0.063812
4    1  1  2  0.093606
5    2  1  2  0.001477
6    0  1  3  0.097736
7    1  1  3  0.043157
8    2  1  3  0.077699

相关问题 更多 >