user13412850
user13412850

Reputation: 519

Python : How do I perform the below Dataframe Operation

I have two dataframes

enter image description here enter image description here

codes are below for the two dfs

import pandas as pd
df1 = pd.DataFrame({'income1': [-13036.0, 1200.0, -12077.5, 1100.0],
                   'income2': [-30360.0, 2000.0, -2277.5, 1500.0],

})


df2 = pd.DataFrame({'name1': ['abc', 'deb', 'hghg', 'gfgf'],
                   'name2': ['dfd', 'dfd1', 'df3df', 'fggfg'],

})

I want to combine the 2 dfs to get a single df with names against the respective income values, as shown below. Any help is appreciated. Please note that I want it in the same sequence as shown in my output.

enter image description here

Upvotes: 1

Views: 38

Answers (2)

Miguel Gonzalez
Miguel Gonzalez

Reputation: 773

Try this:

incomes = pd.concat([df1.income1, df1.income2], axis = 0)
names   = pd.concat([df2.name1  , df2.name2]  , axis = 0)

df = pd.DataFrame({'Name': names, 'Incomes': incomes})

Upvotes: 0

jezrael
jezrael

Reputation: 862641

Here is possible convert values to numpy array and flatten with pass to DataFrame cosntructor:

df = pd.DataFrame({'Name': np.ravel(df2.to_numpy()), 
                   'Income': np.ravel(df1.to_numpy())})
print (df)

    Name   Income
0    abc -13036.0
1    dfd -30360.0
2    deb   1200.0
3   dfd1   2000.0
4   hghg -12077.5
5  df3df  -2277.5
6   gfgf   1100.0
7  fggfg   1500.0

Or concat with DataFrame.stack and Series.reset_index for default index values:

df = pd.concat([df2.stack().reset_index(drop=True), 
                df1.stack().reset_index(drop=True)],axis=1, keys=['Name','Income'])
print (df)
    Name   Income
0    abc -13036.0
1    dfd -30360.0
2    deb   1200.0
3   dfd1   2000.0
4   hghg -12077.5
5  df3df  -2277.5
6   gfgf   1100.0
7  fggfg   1500.0

Upvotes: 3

Related Questions