【问题标题】:How to Remove a Substring of String in a Dataframe Column?如何删除数据框列中的字符串子字符串?
【发布时间】:2016-12-07 00:05:54
【问题描述】:

我有这个简化的数据框:

ID, Date
1 8/24/1995
2 8/1/1899 :00

如何使用 pandas 的强大功能来识别数据框中具有额外 :00 的任何日期并将其删除。

知道如何解决这个问题吗?

我尝试过这种语法但没有帮助:

df[df["Date"].str.replace(to_replace="\s:00", value="")]

输出应该是这样的:

ID, Date
1 8/24/1995
2 8/1/1899

【问题讨论】:

  • 您是自己创建数据框吗?因为您可以在制作 df 之前删除无关的 :00
  • 我正在使用 pd.read.csv() 将 .csv 文件作为数据框读取...但我注意到,在将它们作为数据框读取之前,某些日期实际上确实有多余的 `:00`

标签: python regex string pandas dataframe


【解决方案1】:

您需要将修剪后的列分配回原始列而不是进行子集化,而且str.replace 方法似乎没有to_replacevalue 参数。它有 patrepl 参数:

df["Date"] = df["Date"].str.replace("\s:00", "")

df
#   ID       Date
#0   1  8/24/1995
#1   2   8/1/1899

【讨论】:

    【解决方案2】:

    要将其应用于整个数据框,我会先 stack 然后 unstack

    df.stack().str.replace(r'\s:00', '').unstack()
    

    功能化

    def dfreplace(df, *args, **kwargs):
        s = pd.Series(df.values.flatten())
        s = s.str.replace(*args, **kwargs)
        return pd.DataFrame(s.values.reshape(df.shape), df.index, df.columns)
    

    示例

    df = pd.DataFrame(['8/24/1995', '8/1/1899 :00'], pd.Index([1, 2], name='ID'), ['Date'])
    
    dfreplace(df, '\s:00', '')
    


    rng = range(5)
    df2 = pd.concat([pd.concat([df for _ in rng]) for _ in rng], axis=1)
    
    df2
    

    dfreplace(df2, '\s:00', '')
    

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 2021-11-08
      • 2023-04-09
      • 2021-02-13
      • 2021-06-24
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多