Home > Net >  How can I add/merge values from one existing column to another column - Python - Pandas - Jupyter No
How can I add/merge values from one existing column to another column - Python - Pandas - Jupyter No

Time:05-18

Good Morning,

This is my code

data = {'Names_Males_GroupA': ['Robert', 'Andrew', 'Gordon', 'Steve'], 'Names_Females_GroupA': ['Brenda', 'Sandra', 'Karen', 'Megan'], 'Name_Males_GroupA': ['David', 'Patricio', 'Noe', 'Daniel']}


df = pd.DataFrame(data)

df

enter image description here

Since Name_Males_GroupA has an error (missing and 's') I need to move all the values to the correct column which is Names_Males_GroupA

In other words: I want to Add the names David, Patricio, Noe and Daniel below the names Robert, Andrew, Gordon and Steve.

After that I can delete the wrong column.

Thank you.

CodePudding user response:

If I understand you correctly, you can try

df = pd.concat([df.iloc[:, :2], df.iloc[:, 2].to_frame('Names_Males_GroupA')], ignore_index=True)
print(df)

  Names_Males_GroupA Names_Females_GroupA
0             Robert               Brenda
1             Andrew               Sandra
2             Gordon                Karen
3              Steve                Megan
4              David                  NaN
5           Patricio                  NaN
6                Noe                  NaN
7             Daniel                  NaN

CodePudding user response:

I would break them apart and put them back together with a pd.concat

data = {'Names_Males_GroupA': ['Robert', 'Andrew', 'Gordon', 'Steve'], 'Names_Females_GroupA': ['Brenda', 'Sandra', 'Karen', 'Megan'], 'Name_Males_GroupA': ['David', 'Patricio', 'Noe', 'Daniel']}
df = pd.DataFrame(data)
df1 = df[['Name_Males_GroupA', 'Names_Females_GroupA']]
df1.columns = ['Names_Males_GroupA', 'Names_Females_GroupA']
df = df[['Names_Males_GroupA', 'Names_Females_GroupA']]
pd.concat([df, df1])
  • Related