Panda dataframe print to console without column names

Viewed 11807

I have a dataframe like:

    0   1   2   3   4   5   6   7   8   class
0   0.4444  0.0000  0.0000  0.0000  0.1111  0.0000  0.2222  0.0000  0.0000  0
1   0.4444  0.3333  0.3333  0.4444  0.6667  1.0000  0.2222  0.1111  0.0000  0
2   0.2222  0.0000  0.0000  0.0000  0.1111  0.1111  0.2222  0.0000  0.0000  0

All I want this to be printed on console without newline and without column names:

0.4444,0.0000,0.0000,0.0000,0.1111,0.0000,0.2222,0.0000,0.0000,0
0.4444,0.3333,0.3333,0.4444,0.6667,1.0000,0.2222,0.1111,0.0000,0
0.2222,0.0000,0.0000,0.0000,0.1111,0.1111,0.2222,0.0000,0.0000,0
..

There are 360 rows in total.

I am new to Pandas and cannot figure out how to achieve this. I tried converting pandas to numpy array, to list and tried printing with print(data, end='') but none worked for me.

Solved:

If any one comes across similar problem , solved using df_to_csv and sys.stdout: df.to_csv(sys.stdout, header=False, index=False, float_format='%.4f')

4 Answers

I tried to do this and I can found this code:

def print_df(df):
   # This code delete index and columns names
   df_ = df.copy()
   df_.columns = ['', '', '', '']
   df_.index = ['' for _ in range(len(df))]
   print(df_)

print_df(df)

Other way that I found, but without right spaces between values for column format:

[print(*row, sep=', ') for row in df.values.tolist()];

Q: How print pandas dataframe without columns

A:

print('\n'.join(df.to_string(index = False).split('\n')[1:]))

Explanation:

dfstr   = df.to_string(index = False) # Make str, possibly remove index
dfrows  = dfstr.split('\n')           # split on rows
dfprint = dfrows[1:]                  # Do not print row 0 (columns)
dfp     = '\n'.join(dfprint)          # Create a single string again
df.to_string(index=False, header=False)

This says, convert the dataframe to a string, but without the index labels and without the column (header) labels.

You can print values in loop with f-strings for 3 digits after decimal with join:

for x in df.values:
    print (','.join(f'{y:.4f}' for y in x))

0.4444,0.0000,0.0000,0.0000,0.1111,0.0000,0.2222,0.0000,0.0000,0.0000
0.4444,0.3333,0.3333,0.4444,0.6667,1.0000,0.2222,0.1111,0.0000,0.0000
0.2222,0.0000,0.0000,0.0000,0.1111,0.1111,0.2222,0.0000,0.0000,0.0000

If want no newline get one row of data:

for x in df.values:
    print (','.join(f'{y:.4f}' for y in x), end='')

0.4444,0.0000,0.0000,0.0000,0.1111,0.0000,0.2222,0.0000,0.0000,0.00000.4444,0.3333,0.3333,0.4444,0.6667,1.0000,0.2222,0.1111,0.0000,0.00000.2222,0.0000,0.0000,0.0000,0.1111,0.1111,0.2222,0.0000,0.0000,0.0000
Related