Questions about Python Pandas dataframe

Asked 2 years ago, Updated 2 years ago, 72 views

colum 1, colum2
a,b,c     30
b,c,f     40
a,g,z     50
.
.
.

In this data frame, I would like to construct column4 by adding the value of column2 corresponding to a.

column3, column4
a        80
b        70
c        70
f        40
g        50
z        50

I would like to get the above result, so I wonder if there is a method of numpy and pandas related.

python numpy pandas dataframe

2022-09-22 19:20

2 Answers

df = pd.DataFrame({'col1': ['a, b, c', 'b, c, f', 'a, g, z'],
                   'col2': [30, 40, 50]})
df1 = df['col1'].str.split(', ', expand=True)
df1.rename({i: 'new_col%s' % i for i in range(df1.shape[1])}, axis=1, inplace=True)
df1['value'] = df['col2']
df1 = df1.melt(['value'], ['new_col%s' % i for i in range(3)], 'col', 'key')
df1.drop(['col'], axis=1, inplace=True)
df1.groupby('key').sum()

I don't know if you're watching this because the question is old.


2022-09-22 19:20

If you use Pandas, you can do this.

>>> import pandas as pd
>>> d = {'col1': [1, 2], 'col2': [3, 4], 'col3': [5,6]}
>>> df = pd.DataFrame(data=d)
>>> df
   col1  col2  col3
0     1     3     5
1     2     4     6
>>> df['col4'] = df[['col1','col2']].sum(axis=1)
>>> df
   col1  col2  col3  col4
0     1     3     5     4
1     2     4     6     6

df.sum(axis=1)This adds everyone's meaning.


2022-09-22 19:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.