[英]Change values in a row of pandas df based on a condition
我有一个如下所示的 df,我需要根据条件更改其中一行的值,以便如果它 > 20 则更改为 20。
col1 col2 col3 col4 col5 col6
row1 str1 str 15.3 25.6 3.5 4.5
row2 str2 str 25.8 55.4 4.5 55
row3 str3 str 35.3 45.8 7.5 65
row4 str4 str 45.2 55.7 6.5 7.5
对于专栏,我尝试了以下方法并且有效:
df.col1 = np.where(df.col1 > 20, 20, df.col1)
然而,对于行,我尝试了使用 loc 和 mask 的多行,但它不起作用。 如果我们取第 3 行,预计 output 是:
col1 col2 col3 col4 col5 col6
row1 str1 str 15.3 25.6 3.5 4.5
row2 str2 str 25.8 55.4 4.5 55
row3 str3 str 20.0 20.0 7.5 20
row4 str4 str 45.2 55.7 6.5 7.5
所以你可以在选择 dtypes 之后做一个 df.clip,然后 combine_first:
rows = ['row3'] #more row indices here in a list
df_out = df.select_dtypes('number').clip(upper=20).loc[rows].combine_first(df)
print(df_out)
col1 col2 col3 col4 col5 col6
row1 str1 str 15.3 25.6 3.5 4.5
row2 str2 str 25.8 55.4 4.5 55.0
row3 str3 str 20.0 20.0 7.5 20.0
row4 str4 str 45.2 55.7 6.5 7.5
IIUC,这应该有效。 您可以使用to_numeric
获取数值, clip
以更改值并fillna
获取字符串值:
df.loc['row3'] = pd.to_numeric(df.loc['row3'], errors='coerce').clip(upper=20).fillna(df.loc['row3'])
Output:
col1 col2 col3 col4 col5 col6
row1 str1 str 15.3 25.6 3.5 4.5
row2 str2 str 25.8 55.4 4.5 55.0
row3 str3 str 20.0 20.0 7.5 20.0
row4 str4 str 45.2 55.7 6.5 7.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.