[英]Get the column index as a value when value exists
I need do create some additional columns to my table or separate table based on following: 我需要根据以下内容为我的表或单独的表创建一些额外的列:
I have a table 我有一张桌子
and I need to create additional columns where the column indexes (names of columns) will be inserted as values. 我需要创建其他列,其中列索引(列的名称)将作为值插入。 Like this: 像这样:
How to do it in pandas? 如何在熊猫中做到这一点? Any ideas? 有任何想法吗? Thank you 谢谢
If need matched columns only for 1
values: 如果只需要匹配1
值的列:
df = (df.set_index('name')
.eq(1)
.dot(df.columns[1:].astype(str) + ',')
.str.rstrip(',')
.str.split(',', expand=True)
.add_prefix('c')
.reset_index())
print (df)
Explanation : 说明 :
Idea is create boolean mask with True
for values which are replaced by columns names - so compare by DataFrame.eq
by 1
and used matrix multiplication by DataFrame.dot
by all columns without first with added separator. 想法是创建具有布尔掩码True
用于由列名称替换值-由这样比较DataFrame.eq
由1
和所使用的矩阵乘法DataFrame.dot
而不先与加入分离器由所有列。 Then remove last traling separator by Series.str.rstrip
and use Series.str.split
for new column, changed columns names by DataFrame.add_prefix
. 然后通过Series.str.rstrip
删除最后一个traling分隔符,并使用Series.str.split
作为新列,通过DataFrame.add_prefix
更改列名。
Another solution: 另一种方案:
df1 = df.set_index('name').eq(1).apply(lambda x: x.index[x].tolist(), 1)
df = pd.DataFrame(df1.values.tolist(), index=df1.index).add_prefix('c').reset_index()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.