简体   繁体   English

附加到 Pandas 中的空 DataFrame?

[英]Appending to an empty DataFrame in Pandas?

Is it possible to append to an empty data frame that doesn't contain any indices or columns?是否可以将 append 转换为不包含任何索引或列的空数据框?

I have tried to do this, but keep getting an empty dataframe at the end.我曾尝试这样做,但最后总是得到一个空的 dataframe。

eg例如

import pandas as pd

df = pd.DataFrame()
data = ['some kind of data here' --> I have checked the type already, and it is a dataframe]
df.append(data)

The result looks like this:结果如下所示:

Empty DataFrame
Columns: []
Index: []

That should work:那应该工作:

>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
   A
0  0
1  1
2  2

But the append doesn't happen in-place , so you'll have to store the output if you want it:但是append不会就地发生,因此如果需要,您必须存储输出:

>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
   A
0  0
1  1
2  2

And if you want to add a row, you can use a dictionary:如果你想添加一行,你可以使用字典:

df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)

which gives you:这给了你:

   age  height name
0    9       2  Zed

You can concat the data in this way:您可以通过以下方式连接数据:

InfoDF = pd.DataFrame()
tempDF = pd.DataFrame(rows,columns=['id','min_date'])

InfoDF = pd.concat([InfoDF,tempDF])

I tried this way and it works我试过这种方式,它有效

import pandas as pd

df = pd.DataFrame(columns =['columnA','columnB'])
data = {'columnA':'data', 'columnB':'data'}
df = df.append(data)

pandas.DataFrame.append Deprecated since version 1.4.0: Use concat() instead. pandas.DataFrame.append自版本 1.4.0 起已弃用:使用concat()代替。

Therefore:所以:

df = pd.DataFrame() # empty dataframe
df2 = pd..DataFrame(...) # some dataframe with data

df = pd.concat([df, df2])

The answers are very useful, but since pandas.DataFrame.append was deprecated (as already mentioned by various users), and the answers using pandas.concat are not "Runnable Code Snippets" I would like to add the following snippet: The answers are very useful, but since pandas.DataFrame.append was deprecated (as already mentioned by various users), and the answers using pandas.concat are not "Runnable Code Snippets" I would like to add the following snippet:

import pandas as pd

df = pd.DataFrame(columns =['name','age'])
row_to_append = pd.DataFrame([{'name':"Alice", 'age':"25"},{'name':"Bob", 'age':"32"}])
df = pd.concat([df,row_to_append])

So df is now:所以df现在是:

    name age
0  Alice  25
1    Bob  32

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

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