编辑Pandas数据框行

2024-07-05 14:59:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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版本?很重要的一点是,这是一个实验,参与者被介绍了大量的试验,每一个试验都收集了不同的数据。


Tags: and数据方法noin版本pandas列表
1条回答
网友
1楼 · 发布于 2024-07-05 14:59:15

如果您真的需要逐行操作,可以使用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]

相关问题 更多 >