【发布时间】:2020-09-25 04:38:05
【问题描述】:
我为每个单元格创建了一个具有二进制值的数据框,其中每一行是用户,每一列是用户可以选择(或不选择)的公司,如下所示:
company1 company2 company3
1 0 0
0 0 1
0 1 1
我创建了一个字典,将每家公司分为高、中、低价值公司:
{'company1': 'high',
'company2': 'low',
'company3': 'low'}
目前有些公司在数据框中但不在字典中,但这应该会很快得到解决。我想为每个用户选择高、中或低价值公司的次数创建变量。最终应该是这样的:
company1 company2 company3 total_low total_mid total_high
1 0 0 0 0 1
0 0 1 1 0 0
0 1 1 2 0 0
我开始创建一个循环来完成此操作,但我不确定如何将列名与字典键/值匹配,或者这是否是最有效的方法(有 ~18,000 行/用户和 ~共 100 列/公司):
total_high = []
total_mid = []
total_low = []
for row in range(df.shape[0]):
for col in range(df.shape[1]):
if df.iloc[row,col] == 1:
# match column name with dict key and add value to
# counter
【问题讨论】:
标签: python pandas loops dataframe dictionary