熊猫列值到行值

pd *_*had 5 python numpy pandas jupyter jupyter-notebook

我有一个数据集(171 列),当我将它放入我的数据框中时,它看起来像这样-

ANO MNO UJ2010  DJ2010   UF2010 DF2010   UM2010 DM2010    UA2010    DA2010 ...
1   A   113   06/01/2010    129 06/02/2010  143 06/03/2010  209 05/04/2010 ...
2   B   218   06/01/2010    211 06/02/2010  244 06/03/2010  348 05/04/2010 ...
3   C   22    06/01/2010    114 06/02/2010  100 06/03/2010  151 05/04/2010 ...
Run Code Online (Sandbox Code Playgroud)

现在我想像这样改变我的数据框 -

    ANO MNO Time        Unit
    1   A   06/01/2010  113
    1   A   06/02/2010  129
    1   A   06/03/2010  143
    2   B   06/01/2010  218
    2   B   06/02/2010  211
    2   B   06/03/2010  244
    3   C   06/01/2010  22
    3   C   06/02/2010  114
    3   C   06/03/2010  100
....
.....
Run Code Online (Sandbox Code Playgroud)

我尝试使用pd.melt,但我认为它不能满足我的目的。我怎样才能做到这一点?

Nic*_*eli 5

使用pd.lreshape作为对接近替代pd.melt过滤列之后的不同标题下被分组。

通过使用 pd.lreshape,当您注入一个字典对象作为它的groups参数时,键将采用新的标题名称,并且作为值提供给它的所有列名称列表dict都将在该单个标题下进行转换。因此,它DF在转换后产生一个长格式。

最后对DF未使用的列进行排序以相应地对齐这些列。

然后,reset_index(drop=True)在末尾的a通过删除中间索引将索引轴重新标记为默认整数值。

d = pd.lreshape(df, {"Time": df.filter(regex=r'^D').columns, 
                     "Unit": df.filter(regex=r'^U').columns})

d.sort_values(['ANO', 'MNO']).reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


如果分组列的长度不匹配,则:

from itertools import groupby, chain

unused_cols = ['ANO', 'MNO']
cols = df.columns.difference(unused_cols)

# filter based on the common strings starting from the first slice upto end.
fnc = lambda x: x[1:] 
pref1, pref2 = "D", "U"

# Obtain groups based on a common interval of slices.
groups = [list(g) for n, g in groupby(sorted(cols, key=fnc), key=fnc)]

# Fill single length list with it's other char counterpart.
fill_missing = [i if len(i)==2 else i + 
                [pref1 + i[0][1:] if i[0][0] == pref2 else pref2 + i[0][1:]]
                for i in groups]

# Reindex based on newly obtained column names.
df = df.reindex(columns=unused_cols + list(chain(*fill_missing)))
Run Code Online (Sandbox Code Playgroud)

继续与pd.lreshape上述相同的步骤,但这次包含dropna=False参数。

  • pd.lreshape 很棒 +1 :-) (2认同)