8

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']"
1
  • Are you willing for a string like "'1','2','3'" or "1,2,3" would do for you? Commented Mar 7, 2019 at 0:50

4 Answers 4

17

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

Sign up to request clarification or add additional context in comments.

Comments

3

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']

Comments

2

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

Comments

0

Try:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.