添加一行数据到DataFrame

这是系列文章,我会按照stackoverflow上pandas相关问题投票数排序进行整理学习。不学习是会变咸鱼的~

原问题:Add one row to pandas DataFrame,要求一行一行地添加数据到已有的空白DataFrame中。

1
2
3
4
5
import pandas as pd
import numpy as np

# 创建空白DataFrame
df = pd.DataFrame(columns=['lib', 'qty1', 'qty2'])

1)使用loc

1
2
3
for i in range(4):
df.loc[i] = [np.random.randint(-1, 1) for n in range(3)]
# df.loc[i] = 5 添加一条数据都为5的记录

2)使用append

1
2
3
4
5
df.append({'lib': 2, 'qty1': 3, 'qty2': 4}, ignore_index=True) 

# append也可以直接添加DataFrame
df2 = pd.DataFrame([[1,2,3], [2,3,4]], columns=['lib', 'qty1', 'qty2'])
df.append(df2, ignore_index=True) # ignore_index设置为True,index将会忽略df2的index

3)重新生成DataFrame

循环将要添加的数据以字典的形式保存到一个列表中,在用列表创建出DataFrame

1
2
3
4
5
6
row_list = [] 
input_rows = [[1,2,3], [2,3,4]] # 待插入数据
for row in input_rows:
dict1 = dict(lib=row[0], qty1=row[1], qty2=row[2]) # 将数据转为字典
row_list.append(dict1) # 保存到列表中
df = pd.DataFrame(row_list)