python-3.x - 如何在一次或多次调用中为多个变量 reshape 数据框,从宽到长?

标签 python-3.x pandas pandas-groupby

我一直无法将下面的数据框改造成长格式:

  df = pd.DataFrame({'id': [66602088802, 85002620928],
     't1': ['car', 'house'],
     't1_pct': [0.46, 0.51],
     't1_valid': [True, True],
     't2': ['bike', 'car'],
     't2_pct': [0.15, 0.07],
     't2_valid': [True, True],
     't3': ['car', 'toy'],
     't3_pct': [0.06, 0.07],
     't3_valid': [False, False]})

    id               t1     t1_pct  t1_valid t2  t2_pct t2_valid    t3  t3_pct  t3_valid
0   66602088802     car     0.46    True    bike    0.15    True    car     0.06    False
1   85002620928     house   0.51    True    car     0.07    True    toy     0.07    False

我想要的结果如下。我尝试使用 pandas.wide_to_long()但到目前为止还没有运气。提前致谢。
    id         test  value     pct     valid
66602088802    1      car     0.46     True
85002620928    1      house   0.51     True
66602088802    2      bike    0.15     True
85002620928    2      car     0.07     True
66602088802    3      car     0.06     False
85002620928    3      toy     0.07     False

先感谢您。

Pandas 0.23.4

python 3.7.1

最佳答案

您可以使用 wide_to_long ;问题只是您的列名需要稍微更改一下,以便 stub 名称为 ['pct', 'valid', 'value'] ,而不是 t# .

import pandas as pd
import numpy as np

# Reverse order of words around '_'
df.columns = ['_'.join(x.split('_')[::-1]) for x in df.columns]
# Add prefix for other stubs
df = df.rename(columns= dict((f't{i}', f'value_t{i}') for i in np.arange(1,4,1)))

pd.wide_to_long(df, stubnames=['pct', 'valid', 'value'], 
                i='id', j='test', suffix='.*', sep='_').reset_index()

输出:
            id test   pct  valid  value
0  66602088802   t1  0.46   True    car
1  85002620928   t1  0.51   True  house
2  66602088802   t2  0.15   True   bike
3  85002620928   t2  0.07   True    car
4  66602088802   t3  0.06  False    car
5  85002620928   t3  0.07  False    toy

关于python-3.x - 如何在一次或多次调用中为多个变量 reshape 数据框,从宽到长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53585298/

相关文章:

python-3.x - 如何使用python删除GKE(Google Kubernetes Engine)集群?

python - Tkinter Notebook 中的可滚动页面

python-3.x - 提取以 'st' ,'nd' 、 'rd' ,'th' 结尾的日期,同时使用 RegEx 将日期与月份交换

python - 为 Pandas 中的多列赋值

python - 如何使用groupby过滤数据框中的重复项?

python - 在 Pandas 的坐标行中只保留最大间隔

python - 传递给模块 __init__() 的隐式参数是什么?

Django时间转换格式

python - 我可以将表从 SQL Server (=MS SQL) 导入到 Python/Pandas 数据框中吗?

python - 在 Pandas 中找到第一个非 NaN 值