【问题标题】:Pandas - Edit Index using pattern / regexPandas - 使用模式/正则表达式编辑索引
【发布时间】:2014-09-05 01:03:24
【问题描述】:

给定一个像这样的数据框:

>>> df
      ix  val1  val2  val3  val4
    1.31     2     3     4     5
    8.22     2     3     4     5
    5.39     2     3     4     5
    7.34     2     3     4     5

是否可以使用replace 之类的东西来编辑索引?

伪代码:(因为df索引没有str属性)

df.index=df.index.str.replace("\\.[0-9]*","")

我需要类似的东西:

>>> df
   ix  val1  val2  val3  val4
    1     2     3     4     5
    8     2     3     4     5
    5     2     3     4     5
    7     2     3     4     5

问题是我的数据框很大。

提前致谢

【问题讨论】:

    标签: python regex pandas dataframe


    【解决方案1】:

    你可以这样做:

    df.index = df.index.to_series().astype(str).str.replace(r'\.[0-9]*','').astype(int)
    

    你也可以使用.extract:

    df.index.to_series().astype(str).str.extract(r'(\d+)').astype(int)
    

    或者,您也可以只使用map 指向int 的索引:

    pd.Index(map(int, df.index))
    

    【讨论】:

    • 谢谢 behzad.nouri。那完成了工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 2012-05-12
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多