Python - 在多列中搜索字符串以设置分类变量值

标签 python pandas

我是 Python 和 Pandas 的新手,我正在尝试使用它对非常大的数据集(1000 万个案例)进行统计分析,因为其他选项(SPSS 和 R)无法处理授权的数据集硬件。

在此分析中,我需要按行搜索一系列列(准确地说是 30 个)以提取单个字符串(大约 200 个是可能的,不确定数据集中实际存在多少),然后创建一个每个字符串的分类变量。

数据是这样的

  Dx1     Dx2     Dx3   etc... 
  001     234     456 
  231     001     444
  245     777     001

需要的是

Dx1     Dx2     Dx3  Var001   Var234  Var456  Var231   etc..   
001     234     456  True     True    True    False
231     001     444  True     False   False   True
245     777     001  True     False   False   False

关于如何做到这一点有什么想法吗?


df.dtypes 显示

AGE                      int64
DISPUNIFORM              int64
DRG                      int64
DRGVER                   int64
Readmit_30D              int64
DXCCS1                   int64
DXCCS2                   int64
DXCCS3                   int64
DXCCS4                   int64
...on to DXCCS30

最佳答案

我认为您希望将“一个热编码”数据集保留为一个稀疏矩阵。

所以尝试下面的内存节省方法:

from sklearn.feature_extraction.text import CountVectorizer

cv = CountVectorizer()

r = pd.SparseDataFrame(cv.fit_transform(df.astype(str).add(' ').sum(axis=1)),
                       columns=cv.get_feature_names(),
                       index=df.index,
                       default_fill_value=0).add_prefix('Var')

结果:

In [85]: r
Out[85]:
   Var001  Var231  Var234  Var245  Var444  Var456  Var777
0       1       0       1       0       0       1       0
1       1       1       0       0       1       0       0
2       1       0       0       1       0       0       1

In [86]: r.memory_usage()
Out[86]:
Index     80
Var001    24
Var231     8
Var234     8
Var245     8
Var444     8
Var456     8
Var777     8
dtype: int64

解释:

为了将所有数据收集到一列中,我使用了以下技巧:

In [89]: df.astype(str).add(' ').sum(axis=1)
Out[89]:
0    001 234 456
1    231 001 444
2    245 777 001
dtype: object

PS 不要将生成的稀疏 DF 与源 DF 连接起来,因为这可能会导致它“爆炸”回正常(非稀疏)DF:

In [87]: df.join(r)
Out[87]:
   Dx1  Dx2  Dx3  Var001  Var231  Var234  Var245  Var444  Var456  Var777
0  001  234  456       1       0       1       0       0       1       0
1  231  001  444       1       1       0       0       1       0       0
2  245  777  001       1       0       0       1       0       0       1

In [88]: df.join(r).memory_usage()
Out[88]:
Index     80
Dx1       24
Dx2       24
Dx3       24
Var001    24
Var231    24
Var234    24
Var245    24
Var444    24
Var456    24
Var777    24
dtype: int64

关于Python - 在多列中搜索字符串以设置分类变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47308363/

相关文章:

python - 如何为 hdf5 正确使用 Pandas 迭代器?

python - Pandas 对齐()函数: illustrative example

python - 重采样后获取 pandas 第 n 个条目(在 'DatetimeIndexResampler' 对象上)

python - 遍历枚举返回括号中的字符串

python - 将 Chrome 历史日期/时间戳转换为可读格式

python - 将文本文件中的字符串(已经是元组格式)转换为元组列表

python - 融化唯一索引的 pandas 数据帧以与 ggplot/rpy2 一起使用

python - 读取 pandas csv 文件时如何重命名值

python - 优化分区函数

python - 返回 peewee ORM 中分组项目的计数