1
import pandas as pd
import numpy as np

df_1 = pd.DataFrame(np.random.randint(1, 10, size=(8, 4)),
                    columns=['col_1', 'col_2', 'col_3', 'col_4'])

df_2 = df_1.filter(items = ['col_1', 'col_2'])

Как мне в df_2 добавить столбец, являющийся суммой col_3 + col_4?

1

3 ответа 3

4
res = df_1.eval("new = col_3 + col_4")[["col_1", "col_2", "new"]]

результат:

In [82]: res
Out[82]:
   col_1  col_2  new
0      8      4   10
1      6      5   16
2      1      6    9
3      3      2    5
4      3      6    4
5      4      7    9
6      3      3   12
7      1      2   13
1
  • 1
    Да, красиво и просто.
    – strawdog
    15 мар 2021 в 22:32
3

Ну это ж азы работы с Pandas совсем уж:

df_2['col_3_4_sum'] = df_1.col_3 + df_1.col_4
3
import pandas as pd
import numpy as np

df_1 = pd.DataFrame(np.random.randint(1, 10, size=(8, 4)),
                    columns=['col_1', 'col_2', 'col_3', 'col_4'])

df_2 = pd.concat([df_1[["col_1", "col_2"]], df_1.assign(colsum=df_1["col_3"]+df_1["col_4"])["colsum"]], axis=1)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.