2 回答

TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個(gè)贊
你可以試試這個(gè):
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貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果你的 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
添加回答
舉報(bào)