2 回答
TA贡献1982条经验 获得超2个赞
你可以试试这个:
columns = df.select_dtypes(int).columns
df["new_col"] = (df.select_dtypes(int)
.gt(0)
.dot(columns.str[-4:] + " ")
.str.split()
.str[0])
df
name count_2017 count_2018 count_2019 new_col
0 joe 0 1 2 2018
1 cindy 0 0 3 2019
2 john 1 1 0 2017
3 wang 0 0 3 2019
TA贡献1809条经验 获得超8个赞
如果你的 DataFrame 看起来像:
name count_2017 count_2018 count_2019
0 joe 0 1 2
1 cindy 0 0 3
2 john 1 1 0
3 wang 0 0 3
然后:
df['new_col'] = df.iloc[:, 1:].apply(lambda x: next(c for v, c in zip(x, x.index) if v!=0).split('_')[-1], axis=1)
print(df)
印刷:
name count_2017 count_2018 count_2019 new_col
0 joe 0 1 2 2018
1 cindy 0 0 3 2019
2 john 1 1 0 2017
3 wang 0 0 3 2019
添加回答
举报