我有一个数据框,其中一些索引包含不需要的字符,主要是括号“(”。循环需要遍历每一行并消除“(”及其后的所有内容。
for index, row in df.iterrows():
index = index[:index.rfind("(")]
newindexlist.append(index)
df.index = newindexlist
问题是它从每个条目中删除了一个额外的字符。例如,当索引为 abcd 时,它会将其更改为 abc。而如果索引是 abcd(blah) 则它将索引条目更改为 abcd。我怎样才能防止它消除多余的字符?
请您参考如下方法:
给定这样一个数据框:
df = pd.DataFrame({'A' : ['one(two)', 'five (three)two', '(blah)two', '1 three blah haha1'], 'B': [100,200,300,400]})
df = df.set_index('A')
B
A
one(two) 100
five (three)two 200
(blah)two 300
three blah haha1 400
df.index = df.index.str.extract('([\s\w]*)\(*')
给你
B
A
one 1
five 2
3
three blah haha 1 4
