DTATSO
DTATSO

Reputation: 349

print dataframe row values and column headers as a string

I am new to both python and pandas so please forgive me as I believe this should be easy. So if I have a pandas dataframe like this:

    col1 col2 col3
0    13   23   93
1    11   99   15
2    88   25   55

and a user specifies they want row 1. How do I print a string like this:

col1 - 11, col2 - 99, col3 - 15

I know I can get at the row by using df.iloc[[1]] but from there I get lost. Thanks in advance

Upvotes: 1

Views: 1860

Answers (1)

pietrodn
pietrodn

Reputation: 569

A possible solution:

", ".join(["{} - {}".format(k, v) for k, v in df.iloc[1].to_dict().items()])
  1. .to_dict() generates the dictionary {'col1': 11, 'col2': 99, 'col3': 15} from the row.
  2. the list comprehension generates a list of "col_name - value" strings
  3. the strings in the list are joined together, glued by ", "

Final result:

col1 - 11, col2 - 99, col3 - 15

Upvotes: 2

Related Questions