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

我创建了一个空DataFrame:

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

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

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

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


当前回答

与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

其他回答

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

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秒

你可以用df。Loc [i],其中索引为i的行将是你在数据框架中指定的行。

>>> import pandas as pd
>>> from numpy.random import randint

>>> df = pd.DataFrame(columns=['lib', 'qty1', 'qty2'])
>>> for i in range(5):
>>>     df.loc[i] = ['name' + str(i)] + list(randint(10, size=2))

>>> df
     lib qty1 qty2
0  name0    3    3
1  name1    2    4
2  name2    2    8
3  name3    2    1
4  name4    9    6

如果你的Dataframe中的所有数据都有相同的dtype,你可以使用NumPy数组。您可以直接将行写入预定义数组,并在最后将其转换为数据框架。 它似乎比转换字典列表还要快。

import pandas as pd
import numpy as np
from string import ascii_uppercase

startTime = time.perf_counter()
numcols, numrows = 5, 10000
npdf = np.ones((numrows, numcols))
for row in range(numrows):
    npdf[row, 0:] = np.random.randint(0, 100, (1, numcols))
df5 = pd.DataFrame(npdf, columns=list(ascii_uppercase[:numcols]))
print('Elapsed time: {:6.3f} seconds for {:d} rows'.format(time.perf_counter() - startTime, numOfRows))
print(df5.shape)

如果你可以提前获得数据帧的所有数据,有一个比追加到数据帧更快的方法:

创建一个字典列表,其中每个字典对应一个输入数据行。 从这个列表创建一个数据帧。

我有一个类似的任务,一行一行地添加到一个数据帧花了30分钟,从字典列表中创建一个数据帧在几秒钟内完成。

rows_list = []
for row in input_rows:

        dict1 = {}
        # get input row in dictionary format
        # key = col_name
        dict1.update(blah..) 

        rows_list.append(dict1)

df = pd.DataFrame(rows_list)               

与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