Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you append the values of the first column to all other columns in a pandas dataframe

I have been trying to search on how to get the value of the first column and append it to the remaining columns in the dataframe but the ones that I have seen need to still make a new column for the new output.

The closest that I found based on what I need is this code.

df['col'] = 'str' + df['col'].astype(str)

Below is a sample of my dataframe

      col1        col2    col3    col4
1  02-04-2017      ND     0.32     0.8
2  02-05-2017      0.3     ND     No Connection

What I want to know is, how can I get this output?

      col1         col2               c ol3                col4
1  02-04-2017   ND|02-04-2017     0.32|02-04-2017      0.8|02-04-2017 
2  02-05-2017   0.3|02-05-2017    ND|02-05-2017        No Connection|02-05-2017
like image 761
kenneth_V Avatar asked Sep 05 '17 01:09

kenneth_V


People also ask

How do I append to a column in pandas?

In pandas you can add/append a new column to the existing DataFrame using DataFrame. insert() method, this method updates the existing DataFrame with a new column. DataFrame. assign() is also used to insert a new column however, this method returns a new Dataframe after adding a new column.

How will you add the value of two columns in a pandas DataFrame to create another column?

By use + operator simply you can combine/merge two or multiple text/string columns in pandas DataFrame. Note that when you apply + operator on numeric columns it actually does addition instead of concatenation.


2 Answers

You can do this a little easily with df.iloc and str.cat:

df.iloc[:, 1:] = df.iloc[:, 1:].apply(lambda x: x.str.cat(df['col1'], sep='|'))   
df

         col1            col2             col3                      col4
1  02-04-2017   ND|02-04-2017  0.32|02-04-2017            0.8|02-04-2017
2  02-05-2017  0.3|02-05-2017    ND|02-05-2017  No Connection|02-05-2017

You could also use df.transform (v0.20 onwards).

df.iloc[:, 1:] = df.iloc[:, 1:].transform(lambda x: x.str.cat(df['col1'], sep='|'))   
df

         col1            col2             col3                      col4
1  02-04-2017   ND|02-04-2017  0.32|02-04-2017            0.8|02-04-2017
2  02-05-2017  0.3|02-05-2017    ND|02-05-2017  No Connection|02-05-2017
like image 70
cs95 Avatar answered Nov 14 '22 23:11

cs95


Fun with assign, add, and radd

df.assign(**df.iloc[:, 1:].astype(str).add(df.col1.radd('|'), 0))

         col1            col2             col3                      col4
1  02-04-2017   ND|02-04-2017  0.32|02-04-2017            0.8|02-04-2017
2  02-05-2017  0.3|02-05-2017    ND|02-05-2017  No Connection|02-05-2017
like image 35
piRSquared Avatar answered Nov 15 '22 00:11

piRSquared