简体   繁体   中英

python : Compute columns of data frames and add them to new columns

I want to make a new column by calculating existing columns. For example df

df no data1 data2 1 10 15 2 51 46 3 36 20......

i want to make this

new_df no data1 data2 data1/-2 data1/2 data2/-2 data2/2 1 10 15 -5 5 -7.5 7.5 2 51 46 -25.5 25.5 -23 23 3 36 20 -18 18 -9 9

but i don't know how to make this as efficient as possible

To create a new df column based on the calculations of two or more other columns, you would have to define a new column and set it equal to your equation. For example:

df['new_col'] = df['col_1'] * df['col_2']

Is this what you mean? :

import pandas as pd

number = [[1,2],[3,4],[5,6],[7,8],[9,10]]

df = pd.DataFrame(number)
df['Data 1/2'] = df[0] / df[1]

And the output:

    0   1   Data 1/2
0   1   2   0.500000
1   3   4   0.750000
2   5   6   0.833333
3   7   8   0.875000
4   9   10  0.900000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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