Pandas 数据框在满足双重标准时更改值

Pandas dataframe change values when it meets dual criteria

我有一个数据框,其数据为:

Run_1   Run_2   Run_3 Avg
5.26    6.08    1.8   2
273     0       0     23  
5.26    6.08    1.8   1

它有形状

(2928, 501)

我想将所有 > 0 的值更改为 0,并将当前所有值设置为 0 到 1,仅针对其名称中包含子字符串 Run_ 的列。列数来自 Run_1, Run_2, ... Run_500。条件更改不会应用于除 Run_1, Run_2, ... Run_500.

以外的任何其他列

所以,期望的输出是:

Run_1   Run_2   Run_3 Avg
0       0        0    2
0       1        1    23  
0       0        0   1

我尝试了以下方法:

    maxGen = np.max(df.filter(regex='Run_').values) + 5555.
    df.loc[df.filter(regex='Run_') > 0] = maxGen

但是我得到错误:

ValueError: cannot copy sequence with size 500 to array axis with dimension 2928

编辑: 数据框中没有负值。

你可以试试这个:

df.assign(**df.filter(like='Run_').eq(0).astype(int))

输出:

   Run_1  Run_2  Run_3  Avg
0      0      0      0    2
1      0      1      1   23
2      0      0      0    1

或者,如果您不喜欢“**”解包,请使用连接:

df.filter(like='Run_').eq(0).astype(int).join(df['Avg'])

转换应该有效

df[[x for x in df.columns if 'Run_' in x]] = df[[x for x in df.columns if 'Run_' in x]].transform(lambda x: x.eq(0).astype(int))

IIUC

df.iloc[:,:-1]=(~df.astype(bool)).astype(int)
df
Out[54]: 
   Run_1  Run_2  Run_3  Avg
0      0      0      0    2
1      0      1      1   23
2      0      0      0    1