I have two rows of a dataframe likeso:
Jan Feb
a 1 3
b 2 4
I want to create a new dataframe row that combines the two rows (by name because I have to do this for multiple sets of rows of the df) into one row like this:
Jan Feb
a 1 3
b 2 4
c 1/2 3/4
And I do not mean just division as the data types of the actual values are string, I want to concatenate. I feel like there has to be an obvious solution but nothing I have found online is working.
CodePudding user response:
Try this:
df.loc['c', :] = df.apply(lambda x: f"{x[0]}/{x[1]}")
print(df)
Output:
Jan Feb
a 1.0 3.0
b 2.0 4.0
c 1/2 3/4
CodePudding user response:
You could do something like this:
df.loc['c', :] = df.apply(lambda x: '/'.join(map(str,x)))
Ouput:
Jan Feb
a 1.0 3.0
b 2.0 4.0
c 1/2 3/4
CodePudding user response:
You can concatenate the strings by first converting the values to strings and then combining them with the operator.
import pandas as pd
df = pd.DataFrame({'Jan': [1, 2], 'Feb': [3, 4]}, index=['a', 'b'])
df.loc['c'] =df.loc['a'].astype(str) '/' df.loc['b'].astype(str)
CodePudding user response:
You can do something like this: (option without loc, don't meen it's better)
df['c'] = df.apply(lambda x: x['a'] '/' x['b'], axis=1)
df.set_index('name', inplace=True)
df = df.transpose()
CodePudding user response:
Try something like this:
def concat_rows(df,idx,sep="/"):
return [sep.join(l) for l in df.loc[idx].values]
df.loc["new_row"] = concat_rows(df,["a","b"],sep="/")
Explanation:
This function allows you to choose the rows to concat and the separator between strings.
Args:
df: pandas dataframe
idx: list of rows to concat
sep: separator between strings. Default = "/"
RESULT:
JAN FEB
a 1 3
b 2 4
new_row 1/3 2/4