Victor
Victor

Reputation: 73

how to do math operations on a pandas columns and save it as a new dataframe

                  a          b           c
6/29/2018   0.744189037 0.251833984 0.632784618
6/30/2018   0.476601558 0.694181607 0.7951655
7/1/2018    0.91376258  0.111712256 0.813708374
7/2/2018    0.849505199 0.037035716 0.973137932

So I am trying to use this data frame and create a new one based off of math operations. So far I have df3 = df2[['a','b']] and df4 = pd.DataFrame(df3[['a']]*2 - df3[['b']]).

To summarize, I want to use df3 and multiple column a by 2 and subtract that value by column b and put the result into a brand new data frame.

The final output that I would want to get too would be

               2*a-b
6/29/2018   1.23654409
6/30/2018   0.259021508
7/1/2018    1.715812903
7/2/2018    1.661974683

However this yields all values of NA.

Upvotes: 5

Views: 36787

Answers (2)

jezrael
jezrael

Reputation: 862591

If need use mul with sub, last to_frame for one column DataFrame:

df1 = df['a'].mul(2).sub(df['b']).to_frame('col')
#same as
#df1 = (df['a'] * 2 - df['b']).to_frame('col')
print (df1)
                col
6/29/2018  1.236544
6/30/2018  0.259022
7/1/2018   1.715813
7/2/2018   1.661975

And for Series:

s = df['a'].mul(2).sub(df['b'])
print (s)
6/29/2018    1.236544
6/30/2018    0.259022
7/1/2018     1.715813
7/2/2018     1.661975
dtype: float64

Upvotes: 8

Geena
Geena

Reputation: 31

ind_df = df['col_a'].apply(lambda x: x*2) - df[col_b']

Upvotes: 3

Related Questions