我必须循环吗?有没有更快的方法来构建虚拟变量?

2024-05-15 08:43:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些植物数据,看起来像(但我有多达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

我试着用熊猫做假人,比如:

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

但是太阳情人应该被编码为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()获取属性,然后访问dataframe伪变量将其更新为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

Tags: df属性countattcol2col1pdfast
2条回答

你所需要的只是在某些方面类似于获得假人, 但你应该换一种方式

定义df的viev,仅限于“属性”列:

attCols = df[['att_1', 'att_2']]

在目标版本中,在此处添加其他“属性”列

然后定义包含唯一属性名称的索引:

colVals = pd.Index(np.sort(attCols.stack().unique()))

第三步是定义一个函数,计算 当前行:

def myDummies(row):
    return pd.Series(colVals.isin(row).astype(int), index=colVals)

最后一步是加入这个函数的应用结果 从附件到每行:

df = df.join(attCols.apply(myDummies, axis=1))

对于示例数据,结果是:

     plant         att_1     att_2  fast growing  sunlover  tall  waterlover
0  plant_a      sunlover      tall             0         1     1           0
1  plant_b    waterlover  sunlover             0         1     0           1
2  plant_c  fast growing  sunlover             1         1     0           0

^{}max一起使用:

c = ['att_1', 'att_2']
df1 = df.join(pd.get_dummies(df[c], prefix='', prefix_sep='').max(axis=1, level=0))
print (df1)
     plant         att_1     att_2  fast growing  sunlover  waterlover  tall
0  plant_a      sunlover      tall             0         1           0     1
1  plant_b    waterlover  sunlover             0         1           1     0
2  plant_c  fast growing  sunlover             1         1           0     0

实际数据中3k行的性能应该不同:

df = pd.concat([df] * 1000, ignore_index=True)


In [339]: %%timeit
     ...: 
     ...: c = ['att_1', 'att_2']
     ...: df1 = df.join(pd.get_dummies(df[c], prefix='', prefix_sep='').max(axis=1, level=0))
     ...: 
     ...: 
10.7 ms ± 1.11 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [340]: %%timeit
     ...: attCols = df[['att_1', 'att_2']]
     ...: colVals = pd.Index(np.sort(attCols.stack().unique()))
     ...: def myDummies(row):
     ...:     return pd.Series(colVals.isin(row).astype(int), index=colVals)
     ...: 
     ...: df1 = df.join(attCols.apply(myDummies, axis=1))
     ...: 
     ...: 
1.03 s ± 22 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

另一个解决方案:

In [133]: %%timeit
     ...: c = ['att_1', 'att_2']
     ...: df1 = (df.join(pd.DataFrame([dict.fromkeys(x, 1) for x in df[c].to_numpy()])
     ...:                  .fillna(0)
     ...:                  .astype(np.int8)))
     ...:                  
13.1 ms ± 723 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

相关问题 更多 >