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
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With