python - Pandas 数据框 : How to print single row horizontally?

标签 python pandas dataframe

DataFrame 的单行并排打印值,即 column_name 然后是 columne_value 在一行中,下一行包含下一个 column_name 和 columne_value。例如下面的代码

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

第一行的输出为

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

有没有办法水平打印每一行并忽略数据类型名称?第一行示例:

0    1    2
100  200  300

最佳答案

使用to_frame方法,然后用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

注意:
这类似于 @JohnE 的回答,因为方法 to_frame 是围绕 pd.DataFrame 的语法糖。

事实上如果我们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

指向_constructor_expanddim

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

你可以看到它简单地返回了可调用的DataFrame

关于python - Pandas 数据框 : How to print single row horizontally?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40622796/

相关文章:

python - 如何使用 Pandas 计算与起始值相比的百分比变化?

python - Scrapy 中使用代理的多线程

python - 如何更改鼠标指针颜色 tkinter?

python - 我可以在程序中多次调用函数 'main' 吗?

python - nltk.tokenize 从 Shell 正确执行,但作为脚本文件出现错误

pandas - Matplotlib 轴上的浮点值而不是整数

python - 如果表 beautifulsoup 和 pandas 中不存在类,则停止抓取 url

python - NA 的 bool 值太模糊

r - 从 R 中的 sapply 函数取回数据帧序列

sql - 如何在 R 数据帧上执行类似 SQL 的操作?