Dick McManus
Dick McManus

Reputation: 789

Convert dataframe row into string of values without column indexes in python

I have a dataframe row and want to get it as a string of just the values, no columns.

col1 | col2 | col3
-----------------
1    | 2    | 3
x    | y    | z

I'd like to be able to select just one row and have it as a string like:

'1','2','3'

But I keep getting the column names still in there, or lots of other values like:

"['1' '2'\n '3']"

Upvotes: 8

Views: 28525

Answers (4)

Magho
Magho

Reputation: 354

just use

df.iloc[1,:].to_string(header=False, index=False)
  1. header = False --> don't include column names in the output string

  2. index = False --> don't include row index in the output string

Upvotes: 17

Rajat Jain
Rajat Jain

Reputation: 2032

Try:

df.apply(lambda x: list(x), 1)

Upvotes: 0

Cedric Zoppolo
Cedric Zoppolo

Reputation: 4743

If you just want a string of the values within row 0 concatenated with , you can do as follows:

import pandas as pd
df = pd.DataFrame({"col1":[1,"x"],"col2":[2,"y"],"col3":[3,"z"]})
l = df.iloc[0,:].apply(str).values
s = ",".join(l)

The list would look like:

>> print l
['1' '2' '3']

And the string you get is:

>> print s
1,2,3

Upvotes: 2

Matt W.
Matt W.

Reputation: 3722

You can use iloc which takes an index and provides the results. iloc[row_indexes, column_indexes]

So df.iloc[0,:] would take the first (0th) row, and all the columns. It'll pass back a Series, so you can use list comprehension [str(x) for x in iterable] to pass back the values as strings.

import pandas as pd

df = pd.DataFrame({'a':[1, 2], 'b':[3, 4], 'c':[5, 6]})

[str(x) for x in df.iloc[0,:]]

['1', '3', '5']

Upvotes: 3

Related Questions