为了账号安全,请及时绑定邮箱和手机立即绑定

使用 pandas 获取该行中第一个非零值的列名

使用 pandas 获取该行中第一个非零值的列名

波斯汪 2023-01-04 16:46:53
我有一个巨大的数据框,但只分享下面的示例。它是一个带有示例标题列名称的 CSV,如下所示。sample.csvcnum,sup1,sup2,sup3,sup4285414459,1,0,1,1445633709,1,0,0,0556714736,0,0,1,01089852074,0,1,0,1cnum 可以在所有 sup* 列中设置 0 或 1。我想选择并打印该 cnum 遇到第一个 1 的列名。之后的所有其他 1 都应忽略,并且不应在输出中打印任何列名。expected output:cnum,supcol285414459,sup1445633709,sup1556714736,sup31089852074,sup2目前我试过这段代码:import pandas as pddf=pd.read_csv('sample.csv')df_union=pd.DataFrame(columns=['cnum','supcol'])for col in df.columns:     df1=df.filter(['cnum']).loc[df[col] == 1]    df1['supcol']=col    df_union=df_union.append(df1)print(df_union)但是,它会打印列名设置为 1 的所有列名。我只想要第一个。请帮忙
查看完整描述

1 回答

?
叮当猫咪

TA贡献1776条经验 获得超12个赞

好像你可以idxmax在这里使用:


df.set_index('cnum').idxmax(axis=1).reset_index(drop=True)


0    sup1

1    sup1

2    sup3

3    sup2

dtype: object


df['output'] = df.set_index('cnum').idxmax(axis=1).reset_index(drop=True) 

# Slightly faster,

# df['output'] = df.set_index('cnum').idxmax(axis=1).to_numpy() 


df

         cnum  sup1  sup2  sup3  sup4 output

0   285414459     1     0     1     1   sup1

1   445633709     1     0     0     0   sup1

2   556714736     0     0     1     0   sup3

3  1089852074     0     1     0     1   sup2

另一个选项dot(将为您提供所有非零列):


d = df.set_index('cnum') 

d.dot(d.columns + ',').str.rstrip(',').reset_index(drop=True)


0    sup1,sup3,sup4

1              sup1

2              sup3

3         sup2,sup4

dtype: object

要么,


(d.dot(d.columns + ',')

  .str.rstrip(',')

  .str.split(',', 1).str[0] 

  .reset_index(drop=True))


0    sup1

1    sup1

2    sup3

3    sup2

dtype: object


查看完整回答
反对 回复 2023-01-04
  • 1 回答
  • 0 关注
  • 147 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信