Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column wise concatenation for each set of values

Tags:

python

pandas

I am trying to append rows by column for every set of 4 rows/values.
I have 11 values the first 4 values should be in one concatenated row and row-5 to row-8 as one value and last 3 rows as one value even if the splitted values are not four.

df_in = pd.DataFrame({'Column_IN': ['text 1','text 2','text 3','text 4','text 5','text 6','text 7','text 8','text 9','text 10','text 11']})

and my expected output is as follows

df_out = pd.DataFrame({'Column_OUT': ['text 1&text 2&text 3&text 4','text 5&text 6&text 7&text 8','text 9&text 10&text 11']})

I have tried to get my desired output df_out as below.

df_2 = df_1.iloc[:-7].agg('&'.join).to_frame()

Any modification required to get required output?

like image 839
san1 Avatar asked Dec 18 '25 20:12

san1


1 Answers

Try using groupby and agg:

>>> df_in.groupby(df_in.index // 4).agg('&'.join)
                     Column_IN
0  text 1&text 2&text 3&text 4
1  text 5&text 6&text 7&text 8
2       text 9&text 10&text 11
>>> 
like image 142
U12-Forward Avatar answered Dec 20 '25 11:12

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!