Home > other >  Concat and Merge columns with another in Pandas Dataframe
Concat and Merge columns with another in Pandas Dataframe

Time:08-18

This what look like my dataframe:

Type Cat tax Car_tax Type_tax
0 Car_1 Car_1_Rent NW;TAX1/Car_1 NW;TAX1/Car_1_Rent
1 Car_2 Car_2_Rent NW;TAX1/Car_2 NW;TAX1/Car_2_Rent
2 Car_3 Car_3_Rent NW;TAX1/Car_3 NW;TAX1/Car_3_Rent
3 Car_4 Car_4_Rent NW;TAX1/Car_4 NW;TAX1/Car_4_Rent
4 Car_5 Car_5_Rent NW;TAX1/Car_5 NW;TAX1/Car_5_Rent
5 Car_6 Car_6_Rent NW;TAX1/Car_6 NW;TAX1/Car_6_Rent
6 Car_7 Car_7_Rent NW;TAX1/Car_7 NW;TAX1/Car_7_Rent
23 Moto_1 Moto_1_Rent NW;TAX1/Moto_1 NW;TAX1/Moto_1_Rent
24 Moto_2 Moto_2_Rent NW;TAX1/Moto_2 NW;TAX1/Moto_2_Rent
25 Moto_3 Moto_3_Rent NW;TAX1/Moto_3 NW;TAX1/Moto_3_Rent
26 Moto_4 Moto_4_Rent NW;TAX1/Moto_4 NW;TAX1/Moto_4_Rent
27 Moto_5 Moto_5_Rent NW;TAX1/Moto_5 NW;TAX1/Moto_5_Rent
28 Moto_6 Moto_6_Rent NW;TAX1/Moto_6 NW;TAX1/Moto_6_Rent
29 Moto_7 Moto_7_Rent NW;TAX1/Moto_7 NW;TAX1/Moto_7_Rent

And this is what I want to achieve :

index Cat Type
0 Car_1 NW;TAX1/Car_1
1 Car_2 NW;TAX1/Car_2
2 Car_3 NW;TAX1/Car_3
3 Car_4 NW;TAX1/Car_4
4 Car_5 NW;TAX1/Car_5
5 Car_6 NW;TAX1/Car_6
6 Car_7 NW;TAX1/Car_7
7 Moto_1 NW;TAX1/Moto_1
8 Moto_2 NW;TAX1/Moto_2
9 Moto_3 NW;TAX1/Moto_3
10 Moto_4 NW;TAX1/Moto_4
11 Moto_5 NW;TAX1/Moto_5
12 Moto_6 NW;TAX1/Moto_6
13 Moto_7 NW;TAX1/Moto_7
14 Car_1_Rent NW;TAX1/Car_1_Rent
15 Car_2_Rent NW;TAX1/Car_2_Rent
16 Car_3_Rent NW;TAX1/Car_3_Rent
17 Car_4_Rent NW;TAX1/Car_4_Rent
18 Car_5_Rent NW;TAX1/Car_5_Rent
19 Car_6_Rent NW;TAX1/Car_6_Rent
20 Car_7_Rent NW;TAX1/Car_7_Rent
21 Moto_1_Rent NW;TAX1/Moto_1_Rent
22 Moto_2_Rent NW;TAX1/Moto_2_Rent
23 Moto_3_Rent NW;TAX1/Moto_3_Rent
24 Moto_4_Rent NW;TAX1/Moto_4_Rent
25 Moto_5_Rent NW;TAX1/Moto_5_Rent
26 Moto_6_Rent NW;TAX1/Moto_6_Rent
27 Moto_7_Rent NW;TAX1/Moto_7_Rent

I have tried many things but with no luck.

CodePudding user response:

Assuming your dataframe is named 'd', have you tried:

a = d[['Cat', 'Car_tax']].rename(columns={'Car_tax':'Type'})
b = d[['tax','Type_tax']]].rename(columns={'Type_tax':'Type', 'tax':'Cat' })
pd.concat([a,b]).reset_index(drop=True)

CodePudding user response:

new_cols = ['Cat', 'Type']

sub_1 = df[['Cat', 'Car_tax']]
sub_2 = df[['tax', 'Type_tax']]
sub_1.columns = sub_2.columns = new_cols

result = pd.concat([sub_1, sub_2]).reset_index(drop=True)

CodePudding user response:

You can just append the columns to each other, there is no merge/concat involved:

import pandas as pd


data = {'car1' : ['car10', 'car11'], 'car2': ['car20', 'car21'], 'car3': ['car30', 'car31'], 'car4': ['car40', 'car41']}
df = pd.DataFrame(data)
car1 = df['car1'].append(df['car2'])
car2 = df['car3'].append(df['car4'])
df2 = pd.DataFrame({'car1': car1, 'car2': car2})
df2 = df2.reset_index(drop=True)
  • Related