[英]Generating a large number of columns based on the unique values in the dataframe
Let's assume that I have the following dataframe: 我们假设我有以下数据帧:
user_id | a1 | a2 | a3 | a4 | a5 | ... | a100
1 | 12 | 30 | 0 | 12 | 1 | ... | 21
2 | 2 | 13 | 18 | 13 | 13 | ... | 3
3 | 42 | 31 | 5 | 14 | 26 | ... | 41
4 | 1 | 9 | 10 | 15 | 20 | ... | 23
Based on this dataframe, I want to generate additional columns for any unique value in the columns of a1-a100. 基于此数据框,我想为a1-a100列中的任何唯一值生成其他列。 I think it is better to explain this with an example.
我认为最好用一个例子来解释这个。 Based on the dataframe above, I would have the following columns appended to the original dataframe:
根据上面的数据框,我将在原始数据框中附加以下列:
1AndAbove | 2AndAbove | ... | 42AndAbove
5 | 4 | ... | 0
6 | 6 | ... | 0
6 | 6 | ... | 2
6 | 5 | ... | 0
For example, the values in the 42AndAbove column shows that only the 3rd user has a value equal to and grater than 42, and it has it twice. 例如,42AndAbove列中的值显示只有第三个用户的值等于和大于42,并且它有两次。
I am able to do this one by one using the following code: 我可以使用以下代码逐个执行此操作:
df['1AndAbove'] = (df > 1).astype(int).sum(axis=1)
However, this is very cumbersome if I need to generate 100 columns. 但是,如果我需要生成100列,这非常麻烦。 I wonder if there is a more generic and elegant way of doing this?
我想知道是否有更通用和优雅的方式来做到这一点?
IIUIC, you can filter a*
columns first, and then loop through the range of 1-2 values check? IIUIC,你可以先过滤
a*
列,然后循环浏览1-2个值的范围吗?
In [382]: df_a = df.filter(like='a')
In [385]: for x in range(1, 43):
...: df['%sAndAbove' % x] = (df_a >= x).sum(axis=1)
...:
Result 结果
In [386]: df
Out[386]:
user_id a1 a2 a3 a4 a5 a100 1AndAbove 2AndAbove 3AndAbove \
0 1 12 30 0 12 1 21 5 4 4
1 2 2 13 18 13 13 3 6 6 5
2 3 42 31 5 14 26 41 6 6 6
3 4 1 9 10 15 20 23 6 5 5
... 33AndAbove 34AndAbove 35AndAbove 36AndAbove 37AndAbove \
0 ... 0 0 0 0 0
1 ... 0 0 0 0 0
2 ... 2 2 2 2 2
3 ... 0 0 0 0 0
38AndAbove 39AndAbove 40AndAbove 41AndAbove 42AndAbove
0 0 0 0 0 0
1 0 0 0 0 0
2 2 2 2 2 1
3 0 0 0 0 0
[4 rows x 49 columns]
Here is the vectorized way to do it: 以下是执行此操作的矢量化方法:
pd.get_dummies(df.stack()).sum(level=0).iloc[:,::-1].cumsum(axis=1).iloc[:,::-1]
Out[83]:
0 1 2 3 5 9 10 12 13 14 15 18 20 21 23 26 30 \
user_id
1 6 5 4 4 4 4 4 4 2 2 2 2 2 2 1 1 1
2 6 6 6 5 4 4 4 4 4 1 1 1 0 0 0 0 0
3 6 6 6 6 6 5 5 5 5 5 4 4 4 4 4 4 3
4 6 6 5 5 5 5 4 3 3 3 3 2 2 1 1 0 0
31 41 42
user_id
1 0 0 0
2 0 0 0
3 3 2 1
4 0 0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.