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
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.
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.
1235 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
776 M2 Mac fails to install rbenv install 3.1.3 due to errors
771 GDB gets version error when attempting to debug with the Presense SDK (IDE)
856 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2025 OneMinuteCode. All rights reserved.