How can I concat strings in a pandas Dataframe row-wise and create a new row out of it?
Here for example, I want to create a new row by concatenating the values in all cells of index 3 and 4.
So the desired row would look like this:
pd.Series([Brand Model, RIVIAN RIT, LUCID Air Drean Edition])
CodePudding user response:
If I understand you right you can use list-comprehension with str.join
for the task:
out = [" ".join(df[c]) for c in df]
print(out)
Prints:
['Brand Model', 'RIVIAN R1T', 'LUCID Air Dream Edition']
DataFrame used:
Col1 Col2 Col3
Index
3 Brand RIVIAN LUCID
4 Model R1T Air Dream Edition
EDIT: To append the row:
df.loc[df.index.max() 1] = [" ".join(df[c]) for c in df]
print(df)
Prints:
Col1 Col2 Col3
Index
3 Brand RIVIAN LUCID
4 Model R1T Air Dream Edition
5 Brand Model RIVIAN R1T LUCID Air Dream Edition