Pandas 清除数据框中的索引名
我有以下建议:Pandas 清除数据框中的索引名,pandas,Pandas,我有以下建议: test1 test2 test3 water(h20) ok x x carbon dioxide (co2) x x x Silicon ok ok ok 我可以通过移除支架和里面的所有东西来清洁df的索引吗 期望输出:
test1 test2 test3
water(h20) ok x x
carbon dioxide (co2) x x x
Silicon ok ok ok
我可以通过移除支架和里面的所有东西来清洁df的索引吗
期望输出:
test1 test2 test3
water ok x x
carbon dioxide x x x
Silicon ok ok ok
我尝试过以下代码:
new_df=df.index.map(lambda x:str(x)[:-5])
和起作用,但不区分带括号(silicon
)的索引名,这是我面临的主要问题,您可以通过regex使用-\s*
选择空白(*
表示0
或更多空白),然后选择()
的内容并用空白替换:
print (df.index.str.replace('\s*\((.*)\)', ''))
Index(['water', 'carbon dioxide', 'Silicon'], dtype='object')
df.index = df.index.str.replace('\s*\((.*)\)', '')
print (df)
test1 test2 test3
water ok x x
carbon dioxide x x x
Silicon ok ok ok
此外,如果需要,请替换第一个(
到结尾,仅删除\)中的所有内容。
:
另一种方式
In [961]: df.index = df.index.str.split('(').str[0]
In [962]: df
Out[962]:
test1 test2 test3
water ok x x
carbon dioxide x x x
Silicon ok ok ok
In [961]: df.index = df.index.str.split('(').str[0]
In [962]: df
Out[962]:
test1 test2 test3
water ok x x
carbon dioxide x x x
Silicon ok ok ok