【发布时间】:2020-09-16 21:56:24
【问题描述】:
我有一些看起来像的植物数据(但我最多有 7 个属性):
Unnamed: 0 plant att_1 att_2 ...
0 0 plant_a sunlover tall
1 1 plant_b waterlover sunlover
2 2 plant_c fast growing sunlover
我尝试使用 pandas get_dummies 之类的:
df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'],'C': [1, 2, 3]})
pd.get_dummies(df, prefix=['col1', 'col2']):
.
C col1_a col1_b col2_a col2_b col2_c
0 1 1 0 0 1 0
1 2 0 1 1 0 0
2 3 1 0 0 0 1
但是 sunlover 应该被编码为 1 但它在 att_1 或 att_2 中。然后我会得到大约 30 个虚拟变量而不是 7 * 30 = 210 个变量。 我试图遍历整个集合并为每个虚拟对象添加值:
for count, plants in enumerate(data_plants.iterrows()):
print("First", count, plants)
for attribute in plants:
print("Second", count, attribute)
代码只是打印,因为我看到了浪费代码的问题。 这项工作,但速度不够快,无法用于 100k 和更多行。我想过使用 .value_counts() 来获取属性,然后访问数据帧虚拟变量以将其更新为 1,但随后我将覆盖该属性。目前,我有点迷茫,没有想法。也许我必须使用其他包?
目标是这样的:
Unnamed: 0 plant att_1 att_2 sunlover waterlover tall ...
0 0 plant_a sunlover tall 1 0 1
1 1 plant_b waterlover sunlover 1 1 0
2 2 plant_c fast growing sunlover 1 0 0
【问题讨论】:
-
您应该在扁平化的数据框值上使用numpy.unique,然后对其进行整形
标签: python pandas variables regression dummy-variable