python - 逐行编辑 Pandas 数据框

标签 python pandas trial

python 的 pandas 很简洁。我正在尝试用 pandas-dataframe 替换字典列表。但是,我想知道是否有一种方法可以同样简单地在 for 循环中逐行更改值?

这是非 pandas 字典版本:

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 引用了它。非常便利!但是字典列表非常不方便,特别是因为我希望能够按列计算 Pandas 擅长的东西。

鉴于上面的 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 在这里保持不变。有没有一种简单的方法可以逐行更新值,也许等同于字典版本?重要的是它是逐行的,因为这是一个实验,在这个实验中,向参与者展示了很多试验,并且在每个试验中收集了各种数据。

最佳答案

如果你真的想要逐行操作,你可以使用 iterrowsloc:

>>> for i, trial in dfTrials.iterrows():
...     dfTrials.loc[i, "response"] = "answer {}".format(trial["no"])
...     
>>> dfTrials
   condition  no  response
0          2   1  answer 1
1          1   2  answer 2
2          1   3  answer 3

[3 rows x 3 columns]

更好的是当你可以向量化时:

>>> dfTrials["response 2"] = dfTrials["condition"] + dfTrials["no"]
>>> dfTrials
   condition  no  response  response 2
0          2   1  answer 1           3
1          1   2  answer 2           3
2          1   3  answer 3           4

[3 rows x 4 columns]

而且总是有apply:

>>> def f(row):
...     return "c{}n{}".format(row["condition"], row["no"])
... 
>>> dfTrials["r3"] = dfTrials.apply(f, axis=1)
>>> dfTrials
   condition  no  response  response 2    r3
0          2   1  answer 1           3  c2n1
1          1   2  answer 2           3  c1n2
2          1   3  answer 3           4  c1n3

[3 rows x 5 columns]

关于python - 逐行编辑 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20692122/

相关文章:

python - Python 中的字符串格式检查

python - 如何通过遍历具有相同键多个值的列表来创建字典?

python - Pandas 使用 Series 过滤 DataFrame

android - 通过应用内计费解锁试用应用程序

c# - 首次运行时和试用期结束后显示“应用程序注册”对话框

trial - 您是否使用 30 天试用服务器进行开发工作?

python - GAE(python)如何需要接收邮件并在留言板上发布然后向所有用户发送邮件?

python - 刷新sqlalchemy中的分离实体

Python __call__ 特殊方法实战示例

python - 使用Pandas向Oracle写入SQL时出错: TypeError: expecting string, unicode或缓冲对象