RangeIndex 对象不可调用

问题描述 投票:0回答:2

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

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 不可调用。如何获取字符串的索引?

python python-3.x pandas indexing slice
2个回答
0
投票

尝试改变

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

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

0
投票

您需要在数据框上运行

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)

我可能没有掌握您想要做的事情的确切细节,但希望这能为您指明正确的方向。

© www.soinside.com 2019 - 2024. All rights reserved.