简体   繁体   English

创建单行 python pandas dataframe

[英]Create single row python pandas dataframe

I want to create a python pandas DataFrame with a single row, to use further pandas functionality like dumping to *.csv. I want to create a python pandas DataFrame with a single row, to use further pandas functionality like dumping to *.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)

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

If you are creating the DataFrame from a dict you can do the following:如果您要从dict创建DataFrame ,您可以执行以下操作:

>>> data = dict(A=1, B=1.23, C='Hello')
>>> df = pd.DataFrame(data, index=[0])
>>> df
   A     B      C
0  1  1.23  Hello

I know this is an old post, but based on this explanation in this post Creating an empty Pandas DataFrame, then filling it?我知道这是一个旧帖子,但是根据这个帖子中的解释创建一个空的 Pandas DataFrame,然后填充它?

We should not be doing dataframe adding.我们不应该添加 dataframe。 I am asking this because I am doing something similar but I opted for the solution in the post I shared over this one.我问这个是因为我正在做类似的事情,但我选择了我分享的帖子中的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM