【问题标题】:Python .str method not working inside an iterrow functionPython .str 方法在 iterrow 函数中不起作用
【发布时间】:2019-10-10 10:48:22
【问题描述】:

我有一个充满文件位置的 pandas 数据框。我正在尝试遍历每一行,打开文件并将其保存为不同的格式。我将文件名从位置字符串中提取出来作为保存路径的一部分。

也就是说,对位置字符串进行切片在 iterrows 函数之外起作用,但在其中会引发错误。

此代码自行运行:

mpo_list['location'].str[31:]

当我把它放在下面的 iterrow 函数中时,我得到一个错误。

import pandas as pd
from PIL import Image
from pathlib import Path

for i, row in mpo_list.iterrows():
    im = Image.open(Path(row['location']))
    picture = row['location'].str[31:]
    im.save('D:\\2018_Formost\\2018-12\\Photos\\'+picture, format = 'JPEG')

这是它抛出的错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-49-483e2a21fc33> in <module>
      2     im = Image.open(Path(row['location']))
      3    # picture = row['location'].str[31:]
----> 4     im.save('D:\\2018_Formost\\2018-12\\Photos\\'+row['location'].str[31:], format = 'JPEG')

AttributeError: 'str' object has no attribute 'str'

谁能看出我犯了什么错误?

【问题讨论】:

  • 试试picture = row['location'][31:]

标签: python pandas iterator


【解决方案1】:

row['location'] 已经是字符串类型,因此您只需要访问正确的索引。试试这个:

picture = row['location'][31:]

【讨论】:

    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 2019-11-19
    • 1970-01-01
    • 2020-07-30
    • 2017-10-16
    • 2021-06-11
    相关资源
    最近更新 更多