Home > front end >  Merge columns after a certain column number and then drop them
Merge columns after a certain column number and then drop them

Time:09-15

I have this dataframe loaded from a CSV where I have to manually combine Col1, Col2 and Col3. Sometimes I have Cols up to Col8 but it is random with the dataset that I am getting.

Here is what the dataset kinda looks like right now

Proto LocalAddress ForeignAdress Col1 Col2 Col3
TCP [0.0.0.0:7] 0.0.0.0:0 LISTENING 4112 tcpsvcs.exe
TCP 0.0.0.0:111 0.0.0.0:0 LISTENING 4 Can not obtain ownership information

What I am doing right now is manually going through each Col's and combining them into one column like here:

ps['Group'] = str(ps['Col6'])   str(ps['Col7'])   str(ps['Col8'])   str(ps['Col9'])   str(ps['Col10'])

and then I drop those old columns using del ps['Col6'], del ps['Col7'], etc.

I was wondering if there is a way to automate this system? Just combining the columns after a certain number of columns? My dataframe looks great until ForeignAddress but would like to automate the process where we just automatically combine everything after a certain column.

This is what the final dataframe should look like:

Proto LocalAddress ForeignAdress CombinedCol
TCP [0.0.0.0:7] 0.0.0.0:0 LISTENING 4112 tcpsvcs.exe
TCP 0.0.0.0:111 0.0.0.0:0 LISTENING 4 Can not obtain ownership information

CodePudding user response:

If need all columns from Col6 to last column:

df = ps.loc[:, 'Col6':]
ps['Group'] = df.astype(str).agg(' '.join, axis=1)
ps = ps.drop(df.columns, axis=1)
  • Related