user8044236
user8044236

Reputation:

Print pandas row in a single string (jupyter notebook)

This code:

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
print(df.loc[0], df.loc[1])

Gives next output:

col1    1
col2    3
Name: 0, dtype: int64 col1    2
col2    4
Name: 1, dtype: int64

But I want something like that (because I want to print a lot of pairs of rows in a cycle from two different dataframes):

1 3, 2 4

Notice that I want to see output in a single row.

Upvotes: 1

Views: 461

Answers (2)

Haleemur Ali
Haleemur Ali

Reputation: 28273

Convert the numpy array to str, and then replace brackets & newlines

This will work generally for dataframes with multiple rows

import re
import pandas as pd
d = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
re.sub(r']|\[', '', str(df.values).replace('\n',','))
# outputs:
'1 3, 2 4'

Upvotes: 0

jezrael
jezrael

Reputation: 862781

Use values for convert Series to 1d numpy array:

print(df.loc[0].values, df.loc[1].values)
[1 3] [2 4]

Or convert to lists:

print(df.loc[0].values.tolist(), df.loc[1].values.tolist())
[1, 3] [2, 4]

Upvotes: 1

Related Questions