假设我有四个连续排列的列作为数据帧的一部分,并且我想用另一个值替换这四个列中的所有负值(比如说(-5),我该怎么做?

T1   T2  T3  T4
20   -5  4   3
85  -78  34  21
-45  22  31  75
-6   5   7  -28

按理说,我希望这能奏效。但事实并非如此。
for i in df.iloc[:,df.columns.get_loc("T1"):df.columns.get_loc("T1")+4]<0:
    for j in df[i]:
        if j<0:
            j=-5

最佳答案

您可以通过应用条件语句来使用indexing

cols = ['T1','T2','T3','T4']
df[df[cols] < 0] = -5

输出
In [35]: df
Out[35]:
     T1  T2  T3  T4
  0  20  -5   4   3
  1  85  -5  34  21
  2  -5  22  31  75
  3  -5   5   7  -5

在您的示例中,您只是替换变量的值。您需要使用at方法替换一个单元格的值。
for i in df.iloc[:,df.columns.get_loc("T1"):df.columns.get_loc("T1")+4]<0:
for index, j in enumerate(df[i]):
    if j<0:
        df.at[index, i] = -5

关于python - 用另一个值替换某些列中的所有负值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50148374/

10-12 16:48
查看更多