0

经过多年的潜伏和阅读帖子,这是我第一次提出 Stack Overflow 问题。

我一直在使用如下所示的无标题 CSV 数据集:

list-of-things-that-are-present-in-this-entry, Yes
list-of-things-that-are-present-in-this-entry, No

每个数据集的大小范围从 ~30KB 到 ~100MB。

现在,就值的数量而言,每个条目的长度都不同。当我使用 Pandas 读取 CSV 文件时,它一直在为我对齐条目——但不是以我想要的方式。

假设第二个条目是两者中较短的一个。Pandas 一直在用 NaN 填充该行的其余部分,因此它与其他条目的长度相同。

list-of-things-that-are-present-in-this-entry, Yes
list-of-things-that-are-present-in-this-entry, No, NaN, NaN

问题是,这会抛出get_dummies我迄今为止尝试使用的功能。“是”和“否”值适用于同一属性。通过“抛出”,我的意思是它一直将每一列值视为相同的属性(例如,Yes 和 NaN,当它应该是 Yes 和 No 进行比较时)。

关于我能做什么的任何建议?或许可以加个头球?我想要的基本上是这样的:

    A B C D E F isThingTrue?
0   0 1 0 1 0 0     0
1   1 0 1 0 0 0     1
2   0 1 1 1 0 1     1

由此:

B, D, No
A, C, Yes
B, C, D, F, Yes

文件本身看起来像这样:

A, B, C, D, E, F, isThingTrue?
0, 1, 0, 1, 0, 0, 0
1, 0, 1, 0, 0, 0, 1
0, 1, 1, 1, 0, 1, 1

我不喜欢熊猫或任何东西;在经历了一百万零五个兔子洞的搜索查询后,我绝望地问了这个问题。这是我第一次涉足数据处理和 Python。如果我做错了什么,请告诉我。

4

1 回答 1

1

您可以使用 scikit-learn CountVectorizer,您需要覆盖令牌模式,因为默认情况下它只捕获 2 个或更多字符的单词。

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer

s = """B, D, No
       A, C, Yes
       B, C, D, F, Yes"""

c = CountVectorizer(token_pattern='\w+')
values = c.fit_transform(s.split('\n'))

pd.DataFrame(values.toarray(), columns=c.vocabulary_)
   a  d  c  yes  f  b  no
0  0  1  0    1  0  1   0
1  1  0  1    0  0  0   1
2  0  1  1    1  1  0   1

您的数据格式并不是真正的 CSV,因此 pandas 可能不是读取它的最佳方式,最好将其作为文本文件读取。

于 2017-02-28T22:31:47.627 回答