How to split all rows in panda Dataframe except one specific row?

I am currently working with pandas.DataFramethat I need to split the entire data frame by a specific value, with the exception of one row. It's easy to split the entire data frame into one value, however I would like one of the rows to be accurate. For example, if I have such a data frame as shown below:

  A      B      C      D
10000  10000  10000  10000 
10000  10000  10000  10000 
10000  10000  10000  10000 
10000  10000  10000  10000 
  1      1      1      1   
10000  10000  10000  10000 
10000  10000  10000  10000 

I want to divide all rows by a value of 1000, except for the 5th row, and I would like all the values ​​to remain unchanged. So, the new dataframe will look like this:

 A   B   C   D
10  10  10  10
10  10  10  10
10  10  10  10
10  10  10  10
 1   1   1   1   
10  10  10  10 
10  10  10  10 

Is there an easy way to do this? I feel that I am missing something very basic. I tried using loc, iloc, mul and div, but can't get them working at the same time.

+4
2

, . .

:

def df_divide_by_excect_row(in_df, divisor, row_to_ignore):
    row_to_save = in_df.iloc[row_to_ignore]
    new_df = in_df / divisor
    new_df.iloc[row_to_ignore] = row_to_save
    return new_df

:

import pandas as pd

df = pd.read_fwf(StringIO(u"""
      A      B      C      D
    10000  10000  10000  10000 
    10000  10000  10000  10000 
    10000  10000  10000  10000 
    10000  10000  10000  10000 
      1      1      1      1   
    10000  10000  10000  10000 
    10000  10000  10000  10000"""), header=1)

print(df)
print(df_divide_by_excect_row(df, 1000, 4))

:

       A      B      C      D
0  10000  10000  10000  10000
1  10000  10000  10000  10000
2  10000  10000  10000  10000
3  10000  10000  10000  10000
4      1      1      1      1
5  10000  10000  10000  10000
6  10000  10000  10000  10000

      A     B     C     D
0  10.0  10.0  10.0  10.0
1  10.0  10.0  10.0  10.0
2  10.0  10.0  10.0  10.0
3  10.0  10.0  10.0  10.0
4   1.0   1.0   1.0   1.0
5  10.0  10.0  10.0  10.0
6  10.0  10.0  10.0  10.0
+3

, , .

n = 1000 
ignored_row = 4
df.iloc[[i for i in range(len(df)) if i != ignored_row], :] /= n
>>> df
    A   B   C   D
0  10  10  10  10
1  10  10  10  10
2  10  10  10  10
3  10  10  10  10
4   1   1   1   1
5  10  10  10  10
6  10  10  10  10

@DSM, :

df.loc[np.arange(len(df)) != 4] /= n
+3

Source: https://habr.com/ru/post/1693225/


All Articles