1

I am trying to add one column at the end of another column. I have included a picture that kind of demonstrates what I want to achieve. How can this be done?

For example, in this case I added the age column under the name column

enter image description here

Dummy data:

{'Unnamed: 0': {0: nan, 1: nan, 2: nan, 3: nan},
 'age ': {0: 35, 1: 56, 2: 22, 3: 16},
 'name': {0: 'andrea', 1: 'juan', 2: 'jose ', 3: 'manuel'},
 'sex': {0: 'female', 1: 'male ', 2: 'male ', 3: 'male '}}
paytonM
  • 21
  • 4

2 Answers2

0

One way is to use .append. If your data is in the DataFrame df:

# Split out the relevant parts of your DataFrame
top_df = df[['name','sex']]
bottom_df = df[['age','sex']]

# Make the column names match
bottom_df.columns = ['name','sex']

# Append the two together
full_df = top_df.append(bottom_df)

You might have to decide on what kind of indexing you want. This method above will have non-unique indexing in full_df, which could be fixed by running the following line: full_df.reset_index(drop=True, inplace=True)

nathan.j.mcdougall
  • 475
  • 1
  • 6
  • 12
0

You can use pd.melt and drop variable column using df.drop here.

df = pd.DataFrame({'Unnamed: 0': {0: np.nan, 1: np.nan, 2: np.nan, 3: np.nan},
                   'age ': {0: 35, 1: 56, 2: 22, 3: 16},
                   'name': {0: 'andrea', 1: 'juan', 2: 'jose ', 3: 'manuel'},
                   'sex': {0: 'female', 1: 'male ', 2: 'male ', 3: 'male '}})

df.melt(id_vars=['sex'], value_vars=['name', 'age']).drop(columns='variable')

      sex   value
0  female  andrea
1   male     juan
2   male    jose
3   male   manuel
4  female      35
5   male       56
6   male       22
7   male       16
Ch3steR
  • 20,090
  • 4
  • 28
  • 58