Pandas dataframe of sums from another dataframe -
i have pandas dataframe. want make dataframe, columns sums of selected columns first frame.
for example in first dataframe have columns named 'a'
, 'b'
, 'c'
, 'd'
. new columns 'x'
, 'y'
, 'x'
has them sum of 'a'
,'b'
, 'c'
, 'y'
contains 'd'
. "mapping" may saved in dictionary: {'x': ['a', 'b', 'c'], y: ['d']}
, not need be.
shall initialize empty data frame keys 'x'
, 'y'
, add columns or there quicker way?
you can directly initialize dataframe data in it:
df2 = pd.dataframe({'x': df[['a', 'b', 'c']].sum(axis=1), 'y': df['d']})
or can build column column:
df2 = df[['a', 'b', 'c']].sum(axis=1).to_frame(name='x') df2['y'] = df['d']
for first column, you'll need call to_frame
name
desired column name. otherwise, df2
series instead of dataframe , you'll have trouble adding columns. after the initial column, can assign columns usual.
sample input:
df = pd.dataframe({'a':[3,1,4],'b':[1,5,9],'c':[2,6,5],'d':[3,5,8]}) b c d 0 3 1 2 3 1 1 5 6 5 2 4 9 5 8
sample output (for either method):
x y 0 6 3 1 12 5 2 18 8
Comments
Post a Comment