1
$\begingroup$

I have a CSV file (such as test1.csv). There are tabular values like the following.

S1     S2     S3
4.6    3.2    2.1
3.2    4.3    5.4
1.4    3.4    6.1

I want to do mathematical operations, such as R1=(S1+S2)/1.5 and R2=(S2+S3)/2.5. Then I want to save the results R1 and R2 in a new CSV file (such as test2.csv). I tried with the following code. That does not work.

import pandas as pd
df = pd.read_csv('test1.csv')
df2['R1'] = (df['S1'] + df['S2'])/1.5
df2['R2'] = (df['S2'] + df['S3'])/2.5
df2.to_csv('test2.csv')
$\endgroup$

2 Answers 2

3
$\begingroup$

You did not define df2 before attempting to use it.

Try this:

import pandas as pd
df = pd.read_csv('test1.csv')
df2 = pd.DataFrame({})
df2['R1'] = (df['S1'] + df['S2'])/1.5
df2['R2'] = (df['S2'] + df['S3'])/2.5
df2.to_csv('test2.csv')
$\endgroup$
0
1
$\begingroup$

You can an array to a dataframe and divide a dataframe by a list of values.

df2 = (df[['S1','S2']]
       .add(df[['S2','S3']].values)
       .div([1.5, 2.5])
       .set_axis(['R1', 'R2'], axis=1)
      )
df2.to_csv('test2.csv')
$\endgroup$
2
  • $\begingroup$ This code would be more readable if it were split into multiple lines. $\endgroup$
    – Galen
    Sep 30, 2022 at 5:28
  • $\begingroup$ Yup, that is much better for reading. $\endgroup$
    – Galen
    Sep 30, 2022 at 5:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.