gmsi gmsi - 9 months ago 68
Python Question

Pandas DataFrame: How to print single row horizontally?

Single row of a DataFrame prints value side by side, i.e. column_name then columne_value in one line and next line contains next column_name and columne_value. For example, below code

import pandas as pd

df = pd.DataFrame([[100,200,300],[400,500,600]])
for index, row in df.iterrows():
# other operations goes here....
print row

Output for first row comes as

0 100
1 200
2 300
Name: 0, dtype: int64

Is there a way to have each row printed horizontally and ignore the datatype, Name? Example for the first row:

0 1 2
100 200 300

Answer Source

use the to_frame method then transpose with T

df = pd.DataFrame([[100,200,300],[400,500,600]])
for index, row in df.iterrows():

     0    1    2
0  100  200  300
     0    1    2
1  400  500  600

This is similar to @JohnE's answer in that the method to_frame is syntactic sugar around pd.DataFrame.

In fact if we follow the code

def to_frame(self, name=None):
    Convert Series to DataFrame
    name : object, default None
        The passed name should substitute for the series name (if it has
    data_frame : DataFrame
    if name is None:
        df = self._constructor_expanddim(self)
        df = self._constructor_expanddim({name: self})

    return df

Points to _constructor_expanddim

def _constructor_expanddim(self):
    from pandas.core.frame import DataFrame
    return DataFrame

Which you can see simply returns the callable DataFrame