我如何创建一个空DataFrame,然后添加行,一个接一个?

我创建了一个空DataFrame:

df = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))

然后我可以在最后添加一个新行,并填充一个字段:

df = df._set_value(index=len(df), col='qty1', value=10.0)

它一次只适用于一个领域。向df中添加新行有什么更好的方法?


当前回答

从python的角度来说:

res = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))
res = res.append([{'qty1':10.0}], ignore_index=True)
print(res.head())

   lib  qty1  qty2
0  NaN  10.0   NaN

其他回答

如果你事先知道条目的数量,你应该通过提供索引来预分配空间(从不同的答案中获得数据示例):

import pandas as pd
import numpy as np
# we know we're gonna have 5 rows of data
numberOfRows = 5
# create dataframe
df = pd.DataFrame(index=np.arange(0, numberOfRows), columns=('lib', 'qty1', 'qty2') )

# now fill it up row by row
for x in np.arange(0, numberOfRows):
    #loc or iloc both work here since the index is natural numbers
    df.loc[x] = [np.random.randint(-1,1) for n in range(3)]
In[23]: df
Out[23]: 
   lib  qty1  qty2
0   -1    -1    -1
1    0     0     0
2   -1     0    -1
3    0    -1     0
4   -1     0     0

速度比较

In[30]: %timeit tryThis() # function wrapper for this answer
In[31]: %timeit tryOther() # function wrapper without index (see, for example, @fred)
1000 loops, best of 3: 1.23 ms per loop
100 loops, best of 3: 2.31 ms per loop

而且,从评论中可以看出,如果尺寸为6000,速度差异会变得更大:

增加数组的大小(12)和行数(500)使 速度上的差异更加显著:313毫秒vs 2.29秒

简单点。通过将一个列表作为输入,该列表将作为一行添加到数据帧中:

import pandas as pd
res = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))
for i in range(5):
    res_list = list(map(int, input().split()))
    res = res.append(pd.Series(res_list, index=['lib', 'qty1', 'qty2']), ignore_index=True)

这将负责向空DataFrame添加一个项。问题是对于第一个索引,df.index.max() == nan:

df = pd.DataFrame(columns=['timeMS', 'accelX', 'accelY', 'accelZ', 'gyroX', 'gyroY', 'gyroZ'])

df.loc[0 if math.isnan(df.index.max()) else df.index.max() + 1] = [x for x in range(7)]

这不是OP问题的答案,而是一个玩具例子来说明ShikharDua的答案,我觉得非常有用。

虽然这个片段很简单,但在实际数据中,我有1000行和许多列,我希望能够根据不同的列进行分组,然后对多个目标列执行下面的统计。因此,有一种可靠的方法来一次一行地构建数据帧是非常方便的。谢谢你,ShikharDua!

import pandas as pd

BaseData = pd.DataFrame({ 'Customer' : ['Acme','Mega','Acme','Acme','Mega','Acme'],
                          'Territory'  : ['West','East','South','West','East','South'],
                          'Product'  : ['Econ','Luxe','Econ','Std','Std','Econ']})
BaseData

columns = ['Customer','Num Unique Products', 'List Unique Products']

rows_list=[]
for name, group in BaseData.groupby('Customer'):
    RecordtoAdd={} #initialise an empty dict
    RecordtoAdd.update({'Customer' : name}) #
    RecordtoAdd.update({'Num Unique Products' : len(pd.unique(group['Product']))})
    RecordtoAdd.update({'List Unique Products' : pd.unique(group['Product'])})

    rows_list.append(RecordtoAdd)

AnalysedData = pd.DataFrame(rows_list)

print('Base Data : \n',BaseData,'\n\n Analysed Data : \n',AnalysedData)

与ShikharDua的答案(基于行)中的字典列表不同,我们也可以将我们的表表示为一个列表字典(基于列),其中每个列表按行顺序存储一列,前提是我们事先知道我们的列。最后,我们构造一次DataFrame。

在这两种情况下,字典键始终是列名。行顺序隐式存储为列表中的order。对于c列和n行,它使用一个c个字典列表,而不是一个n个字典列表。字典列表方法让每个字典冗余地存储所有键,并且需要为每一行创建一个新字典。这里我们只追加到列表中,这总体上是相同的时间复杂度(向列表和字典中添加条目都是平摊常数时间),但由于操作简单,开销可能更小。

# Current data
data = {"Animal":["cow", "horse"], "Color":["blue", "red"]}

# Adding a new row (be careful to ensure every column gets another value)
data["Animal"].append("mouse")
data["Color"].append("black")

# At the end, construct our DataFrame
df = pd.DataFrame(data)
#   Animal  Color
# 0    cow   blue
# 1  horse    red
# 2  mouse  black