为 One-Hot 编码重构 Pandas 中的数据?
Restructure data in Pandas for One-Hot Encoding?
这是我潜伏和阅读帖子多年后第一次提出 Stack Overflow 问题。
我一直在使用 headerless 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' 和 'No' 值用于相同的 属性。通过 "throws off",我的意思是它一直将每一列值视为相同的 属性(例如,Yes 和 NaN,当它应该是 Yes 和 No 进行比较时)。
对我可以做什么有什么建议吗?也许加上 header?我想要的本质上是这样的:
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
我不拘泥于 Pandas 或任何东西;在搜索了一百万零五个兔子洞之后,我是出于绝望才问的。这是我第一次涉足数据处理和 Python。如果我做错了什么,请告诉我。
您可以使用 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 可能不是读取它的最佳方式,最好将其作为文本文件读取。
这是我潜伏和阅读帖子多年后第一次提出 Stack Overflow 问题。
我一直在使用 headerless 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' 和 'No' 值用于相同的 属性。通过 "throws off",我的意思是它一直将每一列值视为相同的 属性(例如,Yes 和 NaN,当它应该是 Yes 和 No 进行比较时)。
对我可以做什么有什么建议吗?也许加上 header?我想要的本质上是这样的:
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
我不拘泥于 Pandas 或任何东西;在搜索了一百万零五个兔子洞之后,我是出于绝望才问的。这是我第一次涉足数据处理和 Python。如果我做错了什么,请告诉我。
您可以使用 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 可能不是读取它的最佳方式,最好将其作为文本文件读取。