【问题标题】:RangeIndex object is not callableRangeIndex 对象不可调用
【发布时间】:2019-08-21 16:04:06
【问题描述】:

我正在从文本文件中读取值并尝试查找子字符串的索引,如下所示

df=pd.read_csv('break_sent.txt', index_col=False,encoding='utf-8',delimiter="\n",names=['sent'])
#print(df[:50])
#df.index = list(df.index)
df1= df[40:50]
print(len(df))
print(df1.index)
print("-------------------------------------------")
for i,row in df1.iterrows():
    string = row['sent']
    #print("string",string)
    d = df1[df1.sent.str.match(string)] # if the result includes more than 1 value then we know that substring and its matching parent string are present, then I will eliminate the substring from the dataframe
    if len(d.index > 2):
        index_val = df.index(string)
        df.drop(df.index(string),inpace=True)
        df.reset_index(level=None, drop=True, inplace=True)

当我运行此代码时,我收到以下错误

Traceback (most recent call last):
  File "process.py", line 15, in <module>
    index_val = df.index(string)
    TypeError: 'RangeIndex' object is not callable

我尝试将范围索引转换为列表

df.index = list(df.index)

但后来我得到 Int64Index is not callable。如何获取字符串的索引?

【问题讨论】:

    标签: python python-3.x pandas indexing slice


    【解决方案1】:

    尝试改变

    df.drop(df.index(string),inpace=True)
    

    df.drop(index=string, inplace=True)
    

    【讨论】:

      【解决方案2】:

      您需要在数据框上运行df.index,而不是在您的搜索字符串上。所以:

      matched_rows = df.index[df1.sent.str.match(string)]
      

      将为您提供与您的字符串匹配的行。然后您应该能够将该输出传递给df.drop

      if len(matched_rows) > 2:
        df.drop(matched_rows, inplace=True)
        df.reset_index(level=None, drop=True, inplace=True)
      

      我可能没有掌握你想要做什么的确切细节,但希望这能指引你正确的方向。

      【讨论】:

        猜你喜欢
        • 2022-10-06
        • 1970-01-01
        • 2021-08-21
        • 2018-09-30
        • 2021-02-18
        • 1970-01-01
        • 2016-10-01
        • 2015-01-29
        • 2014-03-17
        相关资源
        最近更新 更多