Pandas DataFrame: how to print one row horizontally?

One line of the DataFrame prints the value next to each other, that is, column_name, then columne_value in one line, and the next line contains the following 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 

The output for the first line comes as

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

Is there a way for each line to print horizontally and ignore the data type, Name? Example for the first line:

 0 1 2 100 200 300 
+6
source share
4 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 to_frame method is the 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 

What you see is just returning a called DataFrame

+5
source

Use the transpose property:

 df.T 0 1 2 0 100 200 300 
+3
source

There seems to be a simpler answer to this question, 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()) 
+3
source

Sorts, combining the two previous answers, you can 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, the following happens: if you extract a row or column from the data framework, you get a series that displays as a column. And it doesn't matter if you execute ser or ser.T , it "looks" like a column. I mean, the series are one-dimensional, not two, but you understand ...

One way or another, you can convert the series to a dataframe with one line. (I changed the name from "row" to "ser" to emphasize what happens above.) You need to first convert the key to a data framework (which will be the default column), and then transpose it.

+2
source

Source: https://habr.com/ru/post/1012358/


All Articles