创建单行 python pandas 数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45504241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:05:34  来源:igfitidea点击:

Create single row python pandas dataframe

pythonpandasdataframe

提问by HeXor

I want to create a python pandas DataFrame with a single row, to use further pandas functionality like dumping to *.csv.

我想用单行创建一个 python pandas DataFrame,以使用更多的 Pandas 功能,如转储到 *.csv。

I have seen code like the following being used, but I only end up with the column structure, but empty data

我已经看到使用如下代码,但我最终只得到了列结构,但数据为空

import pandas as pd

df = pd.DataFrame()
df['A'] = 1
df['B'] = 1.23
df['C'] = "Hello"
df.columns = [['A','B','C']]

print df

Empty DataFrame
Columns: [A, B, C]
Index: []

While I know there are other ways to do it (like from a dictionary), I want to understand why this piece of code is not working for me!? Is this a version issue? (using pandas==0.19.2)

虽然我知道还有其他方法可以做到(例如从字典中),但我想了解为什么这段代码对我不起作用!?这是版本问题吗?(使用熊猫==0.19.2)

回答by MaxU

In [399]: df = pd.DataFrame(columns=list('ABC'))

In [400]: df.loc[0] = [1,1.23,'Hello']

In [401]: df
Out[401]:
   A     B      C
0  1  1.23  Hello

or:

或者:

In [395]: df = pd.DataFrame([[1,1.23,'Hello']], columns=list('ABC'))

In [396]: df
Out[396]:
   A     B      C
0  1  1.23  Hello