Home > Net >  Joining values from a DataFrame row with comma being separator
Joining values from a DataFrame row with comma being separator

Time:05-20

My DataFrame row line = fd.iloc[0] is:

id                         31458598
total_matched             104671.25
market           Under 3.5 Goals FT
one                               0
two                               0
three                             0
four                              0
five                              0
Name: 0, dtype: object

I have join this values with comma, like this:

f"{line['id']},{line['total_matched']},{line['market']},{line['one']},{line['two']},{line['three']},{line['four']},{line['five']}\n"

But this method is archaic, so I tried to use join:

','.join(line)   '\n'
TypeError: sequence item 0: expected str instance, numpy.int64 found
line.join(',')   '\n'
AttributeError: 'Series' object has no attribute 'join'

What is the correct way to join these values with a comma?

CodePudding user response:

You can use str.cat after ensuring you have strings:

line.astype(str).str.cat(sep=',')

output: '31458598,104671.25,Under 3.5 Goals FT,0,0,0,0,0,0'

CodePudding user response:

You can use this to combine all of your columns into a single column

df['Combo'] = df[[x for x in df.columns]].apply(lambda x: ' '.join(x), axis = 1)

You can add this if statement if you would like to remove any of the columns in your for loop

df['Combo'] = df[[x for x in df.columns if x != column_to_exclude]].apply(lambda x: ' '.join(x), axis = 1)
  • Related