【发布时间】:2014-01-08 15:17:10
【问题描述】:
python 的 pandas 很整洁。我正在尝试用熊猫数据框替换字典列表。但是,我想知道有没有一种方法可以像在 for 循环中那样简单地逐行更改值?
这是非熊猫的字典版本:
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 引用了它。非常便利!但是字典列表非常不方便,特别是因为我希望能够按列计算熊猫擅长的东西。
因此,鉴于上面的 trialList,我虽然可以通过类似 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-version?重要的是,它是逐行的,因为这是一个实验,其中向参与者展示了许多试验,并且每次试验都会收集各种数据。
【问题讨论】: