python - 在 Pandas 中读取自定义稀疏格式
问题描述
我正在尝试阅读以下格式并将其保存在数据框中。
0 21:1.00 42:1.00 63:1.00
0 9: .18 18: .82 32: .15 36: .62
1 8:1.00 22: .06
...
格式包括:
- 第一个整数是样本的类别(这是一个分类数据集)
- 以下是属性。例如,在第一行中,
21:1.00
表示该属性21
的值为 1。
我面临的问题是这是数据集的稀疏表示,我想要类似的东西:
class attr0 attr1 attr2 ... attrn
0 0 0 1 ... 3
密集的表示
解决方案
一种方法是将值拆分并扩展为两列,然后转换为int
和float
。
然后旋转,使第一列成为列标题,第二列成为值。
然后通过添加 attr_ 前缀来清理显示,并将索引列重命名为类:
import pandas as pd
df = pd.DataFrame({0: ["21:1.00", "42:1.00", "63:1.00", None],
1: ["9: .18", "18: .82", "32: .15", "36: .62"],
2: ["8:1.00", "22: .06", None, None]})
df = df.stack() \
.str.split(':', expand=True) \
.astype({0: int, 1: float}) \
.droplevel(0) \
.reset_index() \
.pivot(index='index', columns=0, values=1) \
.reset_index() \
.add_prefix('attr') \
.fillna(0) \
.rename(columns={'attrindex': 'class'})
print(df.to_string(index=False))
输出:
类 attr8 attr9 attr18 attr21 attr22 attr32 attr36 attr42 attr63 0 0.0 0.00 0.00 1.0 0.00 0.00 0.00 1.0 1.0 1 0.0 0.18 0.82 0.0 0.00 0.15 0.62 0.0 0.0 2 1.0 0.00 0.00 0.0 0.06 0.00 0.00 0.0 0.0
展开成多列
df = df.stack() \
.str.split(':', expand=True) \
.astype({0: int, 1: float})
print(df.to_string())
0 1
0 0 21.0 1.00
1 9.0 0.18
2 8.0 1.00
1 0 42.0 1.00
1 18.0 0.82
2 22.0 0.06
2 0 63.0 1.00
1 32.0 0.15
3 1 36.0 0.62
转成所需格式
df = df \
.droplevel(0) \
.reset_index() \
.pivot(index='index', columns=0, values=1) \
.reset_index()
print(df.to_string())
0 index 8 9 18 21 22 32 36 42 63
0 0 NaN NaN NaN 1.0 NaN NaN NaN 1.0 1.0
1 1 NaN 0.18 0.82 NaN NaN 0.15 0.62 NaN NaN
2 2 1.0 NaN NaN NaN 0.06 NaN NaN NaN NaN
清理、重命名等
df = df \
.add_prefix('attr') \
.fillna(0) \
.rename(columns={'attrindex': 'class'})