如何遍历Pandas DataFrame行并按条件设置新列值?
问题:统一狗狗评分至10分制
我正在做学校项目,不要提供完整答案。我有一个名为twitter_archive的Pandas DataFrame,包含狗狗图片评分的分子(rating_numerator)和分母(rating_denominator):单只狗时满分10分,多只狗时满分是狗的数量×10。我想把所有评分统一成10分制,比如5只狗的40/50要调整为8/10。
以下是我的示例代码,我知道第3行语法有误,但它能准确表达我的需求:
twitter_archive['new_denom'] = 10 twitter_archive['new_numer'] = 0 for numer, denom in twitter_archive['rating_numerator','rating_denominator']: if (denom > 10) & (denom % 10 == 0): num_denom = denom / 10 new_numer = numer / num_denom twitter_archive['new_numer'] = new_numer
我的逻辑是:检查分母是否大于10且能被10整除,若是则计算分母是10的多少倍,再将分子除以该倍数得到新分子。目前我的问题是无法将计算得到的新值对应到对应行的新列中。
该DataFrame的头部数据如下:
{'tweet_id': {0: 8.924206435553362e+17, 1: 8.921774213063434e+17, 2: 8.918151813780849e+17, 3: 8.916895572798587e+17, 4: 8.913275589266883e+17}, 'timestamp': {0: Timestamp('2017-08-01 16:23:56+0000', tz='UTC'), 1: Timestamp('2017-08-01 00:17:27+0000', tz='UTC'), 2: Timestamp('2017-07-31 00:18:03+0000', tz='UTC'), 3: Timestamp('2017-07-30 15:58:51+0000', tz='UTC'), 4: Timestamp('2017-07-29 16:00:24+0000', tz='UTC')}, 'text': {0: "This is Phineas. He's a mystical boy. Only ever appears in the hole of a donut. 13/10 ", 1: "This is Tilly. She's just checking pup on you. Hopes you're doing ok. If not, she's available for pats, snugs, boops, the whole bit. 13/10 ", 2: 'This is Archie. He is a rare Norwegian Pouncing Corgo. Lives in the tall grass. You never know when one may strike. 12/10 ', 3: 'This is Darla. She commenced a snooze mid meal. 13/10 happens to the best of us ', 4: 'This is Franklin. He would like you to stop calling him "cute." He is a very fierce shark and should be respected as such. 12/10 #BarkWeek '}, 'rating_numerator': {0: 13.0, 1: 13.0, 2: 12.0, 3: 13.0, 4: 12.0}, 'rating_denominator': {0: 10.0, 1: 10.0, 2: 10.0, 3: 10.0, 4: 10.0}, 'name': {0: 'phineas', 1: 'tilly', 2: 'archie', 3: 'darla', 4: 'franklin'}, 'doggo': {0: 'None', 1: 'None', 2: 'None', 3: 'None', 4: 'None'}, 'floofer': {0: 'None', 1: 'None', 2: 'None', 3: 'None', 4: 'None'}, 'pupper': {0: 'None', 1: 'None', 2: 'None', 3: 'None', 4: 'None'}, 'puppo': {0: 'None', 1: 'None', 2: 'None', 3: 'None', 4: 'None'}}
提示方向
- 遍历DataFrame行的正确方式不是直接取两列迭代,可尝试用
twitter_archive[['rating_numerator','rating_denominator']].iterrows(),这样能拿到每行的索引和对应值 - 计算出
new_numer后,需要通过行索引定位赋值,比如twitter_archive.loc[index, 'new_numer'] = new_numer,而非直接给整列赋值,这样才能修改对应行的值 - Pandas更推荐向量化操作替代循环,可考虑用
np.where或布尔索引批量处理符合条件的行,效率更高
内容的提问来源于stack exchange,提问作者Christian Love
相关产品推荐
相关产品推荐

