简体   繁体   English

根据条件更改 pandas df 一行中的值

[英]Change values in a row of pandas df based on a condition

I have a df that looks like below and I need to change value of one of the rows based on a condition so that if it is > 20 it is changed to 20.我有一个如下所示的 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

For columns I have tried the below and which worked:对于专栏,我尝试了以下方法并且有效:

df.col1 = np.where(df.col1 > 20, 20, df.col1)

For rows however I tried multiple line with loc and mask but it just doesn't work.然而,对于行,我尝试了使用 loc 和 mask 的多行,但它不起作用。 If we take row3 expected output is:如果我们取第 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

So you can do a df.clip after selecting the dtypes and then combine_first:所以你可以在选择 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, this should work. IIUC,这应该有效。 You could use to_numeric to get the numeric values, clip to change values and fillna get string values back:您可以使用to_numeric获取数值, clip以更改值并fillna获取字符串值:

df.loc['row3'] = pd.to_numeric(df.loc['row3'], errors='coerce').clip(upper=20).fillna(df.loc['row3'])

Output: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM