首页 > 解决方案 > 规范化多值列

问题描述

我有这样的数据集:

data = {'Host': ['A','A','A', 'A'], 'Seq': ['0, 1, 2, 99',' 4, 5, 6', '999, 8', '100']}

df = pd.DataFrame(data)

我想标准化所有值。

首先我去这个形状:

host Seq
 A    0
 A    1
 A    2
 A    99
 A    4
 A    5
 A    6
 A    999
 A    8
 A    100

通过此代码:

df.join(df.pop('Seq')
                .str.split(',',expand=True)
                .stack()
                .reset_index(level=1, drop=True)
                .rename('Seq')).reset_index(drop=True)

通过 StandartScaler 标准化后:

df['Seq'] = scaler.fit_transform(np.array(df.Seq.values).reshape(-1, 1)).reshape(-1)

现在我不知道如何返回开始视图。等待想法和评论

标签: pythonpandasnumpy

解决方案


假设您没有破坏原始索引信息

d_ = df.assign(Seq=df.Seq.str.split(',\s*')).explode('Seq')

d_

  Host  Seq
0    A    0
0    A    1
0    A    2
0    A   99
1    A    4
1    A    5
1    A    6
2    A  999
2    A    8
3    A  100

然后你可以按索引和'Host'列分组

d_.groupby([d_.index, 'Host']).Seq.apply(', '.join).reset_index('Host')

  Host          Seq
0    A  0, 1, 2, 99
1    A      4, 5, 6
2    A       999, 8
3    A          100

推荐阅读