简体   繁体   English

在指定字符后删除字符串状索引的字符

[英]Remove characters of string-like index after specified character

Is there a way to remove the characters after a specified character in an index for a Pandas DataFrame? 有没有一种方法可以删除Pandas DataFrame索引中指定字符之后的字符?

I have been using the censusdata package for some data analysis and it outputs the data to a DataFrame with the index as the censusgeo info (eg Anaheim city, California: Summary level: 160, state:06 place:02000) I want to change the index to only be 'Anaheim city, California'. 我一直在使用censusdata软件包进行某些数据分析,并将其输出到索引为人口普查信息的DataFrame(例如,加利福尼亚州阿纳海姆市:摘要级别:160,州:06地点:02000),我想更改索引只能是“加利福尼亚州阿纳海姆市”。 What is the best way to do this? 做这个的最好方式是什么? Is it possible in python? 有可能在python中吗? Could it be easier to do in html? 在HTML中做起来容易吗? I am already using DataFrame.to_html() as my output. 我已经在使用DataFrame.to_html()作为输出。

Thanks 谢谢

An example: 一个例子:

"Anaheim city, California: Summary level: 160, state:06 place:02000".split(":",maxsplit=1)[0]                        
Out: 'Anaheim city, California'

Replace the old index with a new one: 用新索引替换旧索引:

newindex= [ idx.split(":",maxsplit=1)[0] for idx in df.index ]
df.index=newindex

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM