python - 规范化多值列
问题描述
我有这样的数据集:
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)
现在我不知道如何返回开始视图。等待想法和评论
解决方案
假设您没有破坏原始索引信息
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
推荐阅读
- html - 如何在 React ant 设计中更改 SELECT 下拉组件的 CSS?
- php - 数据表未显示在视图页面上
- javascript - 在 vuejs 中加载更多按钮
- angular - 如何正确使用 Angular 5 中的 FileSaver?
- excel - 从 Excel 创建 Outlook 应用程序会生成类型不匹配错误
- git - 如何在冲突中将文件拆分为我们的文件和他们的文件
- java - 更衣室问题推广到 n 个人 - 重复错误
- javascript - 如何测试 JavaScript 对象是否只有特定的字段/属性
- java - 如何在android上从latlan获取地址
- javascript - 没有从反应js中的事件调用函数