背景
需求很简单,往一个已经存在的DataFrame数据中增加一条记录。
假设
有一个投资记录数据名称为data,其类型和值如下所示,现在需要添加一条交易记录,如何处理?
<class 'pandas.core.frame.DataFrame'>
amount deal_time direction id price total_invest
0 300 20180125 1 600660 21.5 0
1 500 20180305 -1 600660 22.4 0
思路
1. 如果记录是dict类型,直接append即可
b = {'deal_time':'20181104','id':'600660','amount':'1000','price':'23.78','direction':'1','total_invest':'0'}
record = record.append(b,ignore_index=True)
2. 如果记录是list类型,则先把单条记录转为Series类型
s = ['20180724','600660','400','22.01','1','0'] #新增的记录
s = pd.Series(s,index=['deal_time','id','amount','price','direction','total_invest'])#list转Series
Series与DataFrame合并有两种方法
- 法1:直接append
record = record.append(s, ignore_index=True)
- 法2:显式指定行进行合并
record.loc[2] = s
参考链接
https://blog.youkuaiyun.com/ai_1046067944/article/details/81382348