我如何创建一个空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中添加新行有什么更好的方法?
当前回答
从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
其他回答
创建一个新记录(数据帧)并添加到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])
你可以使用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)
另一种方法(可能不是很有效):
# add a row
def add_row(df, row):
colnames = list(df.columns)
ncol = len(colnames)
assert ncol == len(row), "Length of row must be the same as width of DataFrame: %s" % row
return df.append(pd.DataFrame([row], columns=colnames))
你也可以像这样增强DataFrame类:
import pandas as pd
def add_row(self, row):
self.loc[len(self.index)] = row
pd.DataFrame.add_row = add_row
如果你有一个数据帧df,想要添加一个列表new_list作为一个新行到df,你可以简单地做:
df.loc[len(df)] = new_list
如果你想在数据帧df下添加一个新的数据帧new_df,那么你可以使用:
df.append(new_df)
在向dataframe添加大量行的情况下,我对性能感兴趣。所以我尝试了四种最流行的方法,并检查了它们的速度。
性能
使用.append (NPE的答案) 使用。loc (fred的回答) 使用.loc预分配(FooBar的答案) 使用dict并最终创建DataFrame (ShikharDua的回答)
运行时结果(秒):
Approach | 1000 rows | 5000 rows | 10 000 rows |
---|---|---|---|
.append | 0.69 | 3.39 | 6.78 |
.loc without prealloc | 0.74 | 3.90 | 8.35 |
.loc with prealloc | 0.24 | 2.58 | 8.70 |
dict | 0.012 | 0.046 | 0.084 |
所以我自己用了加法法。
代码:
import pandas as pd
import numpy as np
import time
del df1, df2, df3, df4
numOfRows = 1000
# append
startTime = time.perf_counter()
df1 = pd.DataFrame(np.random.randint(100, size=(5,5)), columns=['A', 'B', 'C', 'D', 'E'])
for i in range( 1,numOfRows-4):
df1 = df1.append( dict( (a,np.random.randint(100)) for a in ['A','B','C','D','E']), ignore_index=True)
print('Elapsed time: {:6.3f} seconds for {:d} rows'.format(time.perf_counter() - startTime, numOfRows))
print(df1.shape)
# .loc w/o prealloc
startTime = time.perf_counter()
df2 = pd.DataFrame(np.random.randint(100, size=(5,5)), columns=['A', 'B', 'C', 'D', 'E'])
for i in range( 1,numOfRows):
df2.loc[i] = np.random.randint(100, size=(1,5))[0]
print('Elapsed time: {:6.3f} seconds for {:d} rows'.format(time.perf_counter() - startTime, numOfRows))
print(df2.shape)
# .loc with prealloc
df3 = pd.DataFrame(index=np.arange(0, numOfRows), columns=['A', 'B', 'C', 'D', 'E'] )
startTime = time.perf_counter()
for i in range( 1,numOfRows):
df3.loc[i] = np.random.randint(100, size=(1,5))[0]
print('Elapsed time: {:6.3f} seconds for {:d} rows'.format(time.perf_counter() - startTime, numOfRows))
print(df3.shape)
# dict
startTime = time.perf_counter()
row_list = []
for i in range (0,5):
row_list.append(dict( (a,np.random.randint(100)) for a in ['A','B','C','D','E']))
for i in range( 1,numOfRows-4):
dict1 = dict( (a,np.random.randint(100)) for a in ['A','B','C','D','E'])
row_list.append(dict1)
df4 = pd.DataFrame(row_list, columns=['A','B','C','D','E'])
print('Elapsed time: {:6.3f} seconds for {:d} rows'.format(time.perf_counter() - startTime, numOfRows))
print(df4.shape)
附注:我相信我的实现并不完美,也许还有一些优化可以做。