如果我有一个表-类似于你在下面看到的。如何编写只在第2-8列之间迭代的for循环,并查看输入参数,并根据for循环中指定的条件替换每行中的值。
例如,如果输入参数是input=40,我想编写一个>=循环,如果它在第2-8列中找到输入参数的值,那么它们的值将被输入参数替换。如果值小于或等于输入参数,则行值将保持不变。
如果有其他方法可以解决这个问题,请随时与我们分享。但是,我希望输出填充指定列中的所有行。
发布于 2020-06-24 08:25:54
我相信这应该行得通。这应该只会更改列列表中大于或等于number变量的列。希望这能有所帮助!(需要将numpy导入为np)
number = 5
columns = ['col1','col2']
df[columns] = np.where(df[columns]>=number,number,df[columns])
发布于 2020-06-24 13:55:43
它类似于this answer
num=40
#where(condition, new value) replace the values where condition is False
df.loc[:, 'Col2':'Col8']= df.loc[:, 'Col2':'Col8'].where(df.loc[:, 'Col2':'Col8'] < num, num)
但是,如果您有列位置而不是列名,则可以用df.iloc[:,[1,7]]
替换df.loc[:, 'Col2':'Col8']
,这会将第2列替换为第8列
示例
d={'Col1':[1,2,3,4,5,6,7],
'Col2':[132, 93, 124, 475, 857, -46, 67],
'Col3':[234, 123, 765, 1452, 542, 2562, 5876],
'Col4':[7, 7 ,4 , 5 , 1, 9,3]}
data=pd.DataFrame(data=d)
print(data)
Col1 Col2 Col3 Col4
0 1 132 234 7
1 2 93 123 7
2 3 124 765 4
3 4 475 1452 5
4 5 857 542 1
5 6 -46 2562 9
6 7 67 5876 3
将Col2中的任何值>=500替换为Col3
data.loc[:, 'Col2':'Col3']=data.loc[:, 'Col2':'Col3'].where(data.loc[:, 'Col2':'Col3'] < 500, 500)
更新后,将Col2中的任何值>=500替换为Col3
print(data)
Col1 Col2 Col3 Col4
0 1 132 234 7
1 2 93 123 7
2 3 124 500 4
3 4 475 500 5
4 5 500 500 1
5 6 -46 500 9
6 7 67 500 3
https://stackoverflow.com/questions/62545217
复制相似问题