【问题标题】:How is index out of range in this case?在这种情况下,索引如何超出范围?
【发布时间】:2021-01-28 09:28:46
【问题描述】:

我正在尝试构建一个函数,用正则表达式替换数据框的日期列。

# import regex
import re

# create a copy of data
data2 = data
loop = len(data2) - data['Date of Publication'].isna().sum()
for i in range (loop):
   if (pd.notna(data2.loc[i]["Date of Publication"])):

        # copy the content of the date into old-value
        old_value = data2.loc[i]["Date of Publication"]

        # regex to match the first 4 digits of the old_value
        new_value = re.findall("\d{4}", str(old_value))

        # replace the old value
        data2.loc[i, 'Date of Publication'] = new_value[0]

它给出了错误

IndexError                                Traceback (most recent call last)
<ipython-input-66-be514cf910bf> in <module>()
     15 
     16         # replace the old value
---> 17         data2.loc[i, 'Date of Publication'] = new_value[0]
     18 

IndexError: list index out of range

【问题讨论】:

  • 既然这不是我们可以运行的程序,这只是一个猜测,但new_value 里面有什么吗?如果re.findall("\d{4}", str(old_value)) 没有找到任何东西怎么办?
  • 你可以试试data2.loc[i:, 'Date of Publication'] = new_value[0]。我只是添加了一个冒号。

标签: python regex pandas dataframe data-cleaning


【解决方案1】:

在 python 中,data2.loc[a, b]data2.loc[a][b] 不同。您的最后一行代码使用了不正确的索引形式。

data2.loc[a,b]data2.loc[(a, b)] 的简写,索引是单个元组。 Numpy 可能会让您感到困惑,因为它会检查索引是否为元组,并以预期的方式处理它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多