Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 673
gmsi Avatar asked Nov 16 '16 01:11

gmsi


2 Answers

use the to_frame method then transpose with T

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

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

note:
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
    Parameters
    ----------
    name : object, default None
        The passed name should substitute for the series name (if it has
        one).
    Returns
    -------
    data_frame : DataFrame
    """
    if name is None:
        df = self._constructor_expanddim(self)
    else:
        df = self._constructor_expanddim({name: self})

    return df

Points to _constructor_expanddim

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

Which you can see simply returns the callable DataFrame

like image 70
piRSquared Avatar answered Nov 08 '22 07:11

piRSquared


Use the transpose property:

df.T

     0    1    2
0  100  200  300
like image 45
Zeugma Avatar answered Nov 08 '22 07:11

Zeugma