我如何创建一个空DataFrame,然后添加行,一个接一个?
我创建了一个空DataFrame:
df = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))
然后我可以在最后添加一个新行,并填充一个字段:
df = df._set_value(index=len(df), col='qty1', value=10.0)
它一次只适用于一个领域。向df中添加新行有什么更好的方法?
我如何创建一个空DataFrame,然后添加行,一个接一个?
我创建了一个空DataFrame:
df = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))
然后我可以在最后添加一个新行,并填充一个字段:
df = df._set_value(index=len(df), col='qty1', value=10.0)
它一次只适用于一个领域。向df中添加新行有什么更好的方法?
当前回答
创建一个新记录(数据帧)并添加到old_data_frame中。
传递一个值列表和相应的列名来创建一个new_record (data_frame):
new_record = pd.DataFrame([[0, 'abcd', 0, 1, 123]], columns=['a', 'b', 'c', 'd', 'e'])
old_data_frame = pd.concat([old_data_frame, new_record])
其他回答
如果你事先知道条目的数量,你应该通过提供索引来预分配空间(从不同的答案中获得数据示例):
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秒
你可以使用pandas.concat()。有关详细信息和示例,请参见合并、连接和连接。
例如:
def append_row(df, row):
return pd.concat([
df,
pd.DataFrame([row], columns=row.index)]
).reset_index(drop=True)
df = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))
new_row = pd.Series({'lib':'A', 'qty1':1, 'qty2': 2})
df = append_row(df, new_row)
mycolumns = ['A', 'B']
df = pd.DataFrame(columns=mycolumns)
rows = [[1,2],[3,4],[5,6]]
for row in rows:
df.loc[len(df)] = row
下面是在Pandas数据框架中添加/追加一行的方法:
def add_row(df, row):
df.loc[-1] = row
df.index = df.index + 1
return df.sort_index()
add_row(df, [1,2,3])
它可以用于在空的或填充的Pandas数据框架中插入/追加一行。
创建一个新记录(数据帧)并添加到old_data_frame中。
传递一个值列表和相应的列名来创建一个new_record (data_frame):
new_record = pd.DataFrame([[0, 'abcd', 0, 1, 123]], columns=['a', 'b', 'c', 'd', 'e'])
old_data_frame = pd.concat([old_data_frame, new_record])