将数据帧从宽转换为长 - pandas [英] Convert dataframe from wide to long - pandas

查看:57
本文介绍了将数据帧从宽转换为长 - pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框:

I have a dataframe like this:

index    S_1 S_2 S_3 S_4
 0        1    0   0   1
 1        1    1  Nan Nan

我正在尝试将其从长改为宽.例如.

I am trying to change it from long to wide. Eg.

index num S
 0     1  1
 0     2  0
 0     3  0
 0     4  1
 1     1  1
 1     2  1
 1     3  Nan
 1     4  Nan

我尝试了以下代码,基于 this 答案,但我收到以下错误:

I have tried the following code, based on this answer, but I get the following error:

matches_df.columns = matches_df.columns.str.split('_', expand=True)

TypeError: 'float' 类型的对象没有 len()

TypeError: object of type 'float' has no len()

为什么我无法在_"上拆分?列中还有其他信息我想保留.

Why am I unable to split on the "_"? There is other information in the columns which I would like to preserve.

推荐答案

pandas.wide_to_long,当列有这样的存根时这很好.

There is pandas.wide_to_long, which is nice when the columns have stubs like that.

import pandas as pd

df.reset_index(inplace=True,drop=True)
df['id'] = df.index
df = pd.wide_to_long(df, stubnames='S_', i='id', j='num').reset_index().rename(columns={'S_':'S'})

#  id num  index    S
#0   0   1      0  1.0
#1   1   1      1  1.0
#2   0   2      0  0.0
#3   1   2      1  1.0
#4   0   3      0  0.0
#5   1   3      1  NaN
#6   0   4      0  1.0
#7   1   4      1  NaN

这篇关于将数据帧从宽转换为长 - pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆