【问题标题】:Remove rows that are not a number or a date from pandas dataframe从熊猫数据框中删除不是数字或日期的行
【发布时间】:2021-01-04 19:26:40
【问题描述】:

我有一个类似于this SO question 的问题,除了我的专栏不仅包含数字和文本,还包含数字、文本和日期。如何删除除数字和日期之外的所有行?

例如,我有一个通用数据框:

id Nums and Dates
1 40
2 1/1/2021
3 AABBC
4 20
5 1/2/2021

移除后应该是这个样子。

id Nums and Dates
1 40
2 1/1/2021
4 20
5 1/2/2021

【问题讨论】:

  • 欢迎来到 StackOverflow!请记住通过单击答案旁边的复选标记来接受最佳解决方案作为答案。谢谢!有关更多信息,请参阅以下内容:meta.stackexchange.com/questions/5234/…

标签: python pandas


【解决方案1】:

您可以使用to_datetimeto_numeric 创建两个检查日期和数字的系列,并使用notnull() 仅保留非空行。传递 errors='coerce' 将 null 返回到非日期/非数字:

dates = pd.to_datetime(df['Nums and Dates'], errors='coerce')
nums = pd.to_numeric(df['Nums and Dates'], errors='coerce')
df[(dates.notnull()) | (nums.notnull())]

Out[1]:
   id  Nums and Dates
0   1              40
1   2        1/1/2021
3   4              20
4   5        1/2/2021

【讨论】:

    【解决方案2】:

    假设您的数据框名称为df,列名称为Nums and Dates,试试这个:

    not_str_values = [value for value in df if type(value) is not str]
    

    然后:

    df = df.loc[df['Nums and Dates'].isin(not_str_values)]
    

    【讨论】:

      【解决方案3】:

      使用包含和正则表达式,您可以一次性完成列。你可以删除 有字母的行。

      df[~df['Nums and Dates'].str.contains(r'[A-Za-z]', regex=True)]
      
      id  Nums and Dates
      0   1   40
      1   2   1/1/2021
      3   4   20
      4   5   1/2/2021
      

      【讨论】:

        猜你喜欢
        • 2018-01-18
        • 2021-03-19
        • 1970-01-01
        • 2021-12-31
        • 2019-06-26
        • 1970-01-01
        • 2018-02-02
        • 1970-01-01
        • 2019-05-01
        相关资源
        最近更新 更多