[英]Adding rows to Pandas dataframe
我正在尝试使用pandas来创建活动分类帐。 我的对象将有一个pandas DataFrame,它将跟踪与该对象关联的余额和事务。
当订单与该对象关联时,我正在努力将单行数据附加到该pandas数据帧。 似乎最常见的答案是“只有在拥有所有数据后才创建框架”,但我无法做到这一点。 我希望能够在我添加新数据时动态计算。
这是我的相关代码(失败):
self.ledger = pd.DataFrame(data={'entry_date' : [pd.Timestamp('1900-01-01')],
'qty' : [np.float64(startingBalance)],
'element_type' : [pd.Categorical(["startingBalance"])],
'avail_bal' : [np.float64(startingBalance)],
'firm_ind' : True,
'deleted_ind' : False,
'ord_id' : ["fooA"],
'parent_ord_id' : ["fooB"] },
columns=ledgerColumnList
)
self.ledger.iloc[-1] = dict({'entry_date' : ['1900-01-02'],
'qty' : [startingBalance],
'element_type' : ["startingBalance"],
'avail_bal' : [startingBalance],
'firm_ind' : [True],
'deleted_ind' : [False],
'ord_id' : ["foofa"],
'parent_ord_id' : ["foofb"] })
这是我得到的错误:
File "C:\Users\MyUser\My Documents\Workspace\myscript.py", line 135, in __init__
'parent_ord_id' : ["foofb"] })
File "C:\Python27\lib\site-packages\pandas\core\indexing.py", line 117, in __setitem__
self._setitem_with_indexer(indexer, value)
File "C:\Python27\lib\site-packages\pandas\core\indexing.py", line 492, in _setitem_with_indexer
setter(item, v)
File "C:\Python27\lib\site-packages\pandas\core\indexing.py", line 422, in setter
s._data = s._data.setitem(indexer=pi, value=v)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 2843, in setitem
return self.apply('setitem', **kwargs)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 2823, in apply
applied = getattr(b, f)(**kwargs)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 636, in setitem
values, _, value, _ = self._try_coerce_args(self.values, value)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 2066, in _try_coerce_args
raise TypeError
TypeError
思考?
1)我怎么能在熊猫中做到这一点?
要么
2)我应该使用哪些更好的东西,它会给我内置的大熊猫计算工具,但更适合我一点一点的数据需求?
你也可以使用df.loc[]
df = pd.DataFrame({'A': [1,2,3,4], 'B': [5,6,7,8], 'C': [9,10,11,12]})
df
A B C
0 1 5 9
1 2 6 10
2 3 7 11
3 4 8 12
new_row = pd.DataFrame({'A': [35], 'B': [27], 'C': [43]})
new_row
A B C
0 35 27 43
df.loc[4] = new_row.loc[0]
df
A B C
0 1 5 9
1 2 6 10
2 3 7 11
3 4 8 12
4 35 27 43
您还可以尝试为新数据创建新的数据帧,然后使用concat
。
为了便于说明,我们采用一个简单的数据帧:
import pandas as pd
df = pd.DataFrame({'a':[0,1,2],'b':[3,4,5]}
print df
>> a b
0 0 3
1 1 4
2 2 5
假设您有新数据进入,值a=4
且b=7
。 创建仅包含新数据的新数据框:
newresults = {'a':[4],'b':[7]}
_dfadd = pd.DataFrame(newresults)
print _dfadd
>> a b
0 4 7
然后连接:
df = pd.concat([df,_dfadd]).reset_index(drop=True)
print df
>> a b
0 0 3
1 1 4
2 2 5
3 4 7
一种方法是使用pandas.DataFrame.append()
:
self.ledger = pd.DataFrame(data={'entry_date' : [pd.Timestamp('1900-01-01')],
'qty' : [np.float64(startingBalance)],
'element_type' : [pd.Categorical(["startingBalance"])],
'avail_bal' : [np.float64(startingBalance)],
'firm_ind' : [True],
'deleted_ind' : [False],
'ord_id' : ["fooA"],
'parent_ord_id' : ["fooB"] },
columns=ledgerColumnList)
df = pd.DataFrame(data={'entry_date' : [pd.Timestamp('1900-01-02')],
'qty' : [np.float64(startingBalance)],
'element_type' : ["startingBalance"],
'avail_bal' : [np.float64(startingBalance)],
'firm_ind' : [True],
'deleted_ind' : [False],
'ord_id' : ["foofa"],
'parent_ord_id' : ["foofb"] },
columns=ledgerColumnList)
self.ledger.append(df)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.