Python的熊猫很漂亮。我正试图用pandas数据框替换字典列表。但是,我想知道有没有一种方法可以像更改for循环中的值一样简单地逐行更改?
以下是非熊猫dict版本:
trialList = [
{'no':1, 'condition':2, 'response':''},
{'no':2, 'condition':1, 'response':''},
{'no':3, 'condition':1, 'response':''}
] # ... and so on
for trial in trialList:
# Do something and collect response
trial['response'] = 'the answer!'
。。。现在trialList
包含更新后的值,因为trial
引用了它。很方便!但是,dict的列表非常不方便,特别是因为我希望能够计算出pandas擅长的内容。
所以考虑到上面的三角架,我想我可以做一些熊猫的事情来让它变得更好,比如:
import pandas as pd
dfTrials = pd.DataFrame(trialList) # makes a nice 3-column dataframe with 3 rows
for trial in dfTrials.iterrows():
# do something and collect response
trials[1]['response'] = 'the answer!'
。。。但是trialList
在这里保持不变。有没有一种简单的方法可以逐行更新值,也许相当于dict版本?很重要的一点是,这是一个实验,参与者被介绍了大量的试验,每一个试验都收集了不同的数据。
如果您真的需要逐行操作,可以使用
iterrows
和loc
:更好的方法是当你可以矢量化:
总有
apply
:相关问题 更多 >
编程相关推荐