#python #pandas #dataframe #lambda #calculated-columns
Вопрос:
Я в бешенстве, и любая помощь была бы признательна. У меня есть фрейм данных python pd. Цель состоит в том, чтобы получить общее число за каждый год. Для этого я должен добавить «freq» столбца «начало» в «freq2» столбца «добавленный год» ТОЛЬКО в том случае, если «начало»совпадает с » добавленным годом».
gender start freq added_year freq2
0 0 1789 89 1790 89
28 0 1790 6 1791 6
31 0 1791 82 1792 82
69 0 1792 4 1793 4
70 0 1793 123 1794 123
the output would be something along the lines of
start freq added_year freq2 total
1790 6 1790 89 95'''
I think I have to do some kind of map/lambda function or a define a function with a series of if statements, but I am confused as to how to do this.
Thank you.
Ответ №1:
Вы могли бы сделать самостоятельное слияние, а затем взять сумму.
df = df[['start','freq']].merge(df[['added_year','freq2']], left_on='start', right_on='added_year')
df['total'] = df['freq'] df['freq2']
Выход
start freq added_year freq2 total
0 1790 6 1790 89 95
1 1791 82 1791 6 88
2 1792 4 1792 82 86
3 1793 123 1793 4 127