pandas:用列名中的最后一个字符替换列中的值

pandas: replace values in column with the last character in the column name

我有一个数据框如下:

import pandas as pd
df = pd.DataFrame({'sent.1':[0,1,0,1],
                'sent.2':[0,1,1,0],
                'sent.3':[0,0,0,1],
                'sent.4':[1,1,0,1]
               })

我试图用列名中的第 5 个字符(这是列名的数字部分)替换非零值,因此输出应该是,

   sent.1  sent.2  sent.3  sent.4
0       0       0       0       4
1       1       2       0       4
2       0       2       0       0
3       1       0       3       4

我已经尝试了以下但它不起作用,

print(df.replace(1, pd.Series([i[5] for i in df.columns], [i[5] for i in df.columns])))

但是当我用列名替换它时,上面的代码有效,所以我不确定哪一部分是错误的。

print(df.replace(1, pd.Series(df.columns,  df.columns)))

由于您处理的是 1 和 0,实际上您可以将数据帧乘以一个范围:

df = df * range(1, df.shape[1] + 1)

输出:

   sent.1  sent.2  sent.3  sent.4
0       0       0       0       4
1       1       2       0       4
2       0       2       0       0
3       1       0       3       4

或者,如果您想从列名中获取数字:

df = df * df.columns.str.split('.').str[-1].astype(int)

您可以在布尔数组上使用字符串乘法根据条件放置字符串,然后 where 恢复零:

mask = df.ne(0)
(mask*df.columns.str[5]).where(mask, 0)

要有整数:

mask = df.ne(0)
(mask*df.columns.str[5].astype(int))

输出:

  sent.1 sent.2 sent.3 sent.4
0      0      0      0      4
1      1      2      0      4
2      0      2      0      0
3      1      0      3      4

还有一个,使用任意条件(此处 s.ne(0)):

df.apply(lambda s: s.mask(s.ne(0), s.name.rpartition('.')[-1]))