如果我有一张桌子,与您在下面看到的类似。如何编写仅在第2-8列之间迭代并查看输入参数并基于for循环中指定的条件的for循环,替换每一行中的值。
例如,如果输入参数为input = 40,我想编写一个for循环,如果它在第2-8列中找到一个值> =该输入参数,则将其值替换为输入参数。如果这些值小于或等于输入参数,则行值将保持不变。
如果还有其他方法可以处理此问题,请随时分享。但是,我希望输出填充指定列中的所有行。
答案 0 :(得分:0)
我认为这应该可行。这仅应更改列列表中大于或等于number变量的列。希望这可以帮助! (需要将numpy导入为np)
number = 5
columns = ['col1','col2']
df[columns] = np.where(df[columns]>=number,number,df[columns])
答案 1 :(得分:0)
类似于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.loc[:, 'Col2':'Col8']
替换为df.iloc[:,[1,7]]
,将第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中的500
data.loc[:, 'Col2':'Col3']=data.loc[:, 'Col2':'Col3'].where(data.loc[:, 'Col2':'Col3'] < 500, 500)
更新后,将Col2中所有大于等于500的值替换为Col3中的500
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