29

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
1
  • 4
    The answer below matches what you want, but a common use-case would be wanting a single line without the header. For that I'd suggest just doing something like list(row) or dict(row). Can easily be formatted such as: '\t'.join(list(row).astype(str)). Commented Apr 5, 2018 at 0:03

4 Answers 4

36

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That was a great recovery ;-) And very good explanation of the difference.
hi, how to do it from horizontal to vertical
10

Use the transpose property:

df.T

     0    1    2
0  100  200  300

4 Comments

What if df has multiple rows like df = pd.DataFrame([[100,200,300],[400,500,600]]). How can each row be printed like that?
Amend your OP you reflect that part of the question and your expected output with such a dataframe
Updated the question. Thanks
What is the output that you want? Do you want each row to be a separate column?
3

It seems like there should be a simpler answer to this, but try turning it into another DataFrame with one row.

data = {x: y for x, y in zip(df.columns, df.iloc[0])}
sf = pd.DataFrame(data, index=[0])
print(sf.to_string())

Comments

3

Sorta combining the two previous answers, you could do:

for index, ser in df.iterrows():
    print( pd.DataFrame(ser).T )

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

Basically what happens is that if you extract a row or column from a dataframe, you get a series which displays as a column. And doesn't matter if you do ser or ser.T, it "looks" like a column. I mean, series are one dimensional, not two, but you get the point...

So anyway, you can convert the series to a dataframe with one row. (I changed the name from "row" to "ser" to emphasize what is happening above.) The key is you have to convert to a dataframe first (which will be a column by default), then transpose it.

1 Comment

I often use a reconstruction to solve problems. plus one from me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.