【问题标题】:Delete the rows that contain the string - Pandas dataframe删除包含字符串的行 - Pandas 数据框
【发布时间】:2019-12-02 07:27:57
【问题描述】:

我想将 DataFrame 中的列从 OBJECT 转换为 INT。我需要完全删除包含字符串的行。

以下表达式“保存”了我关心的数据,并将列从 OBJECT 转换为 INT 类型:

df["column name"] = df["column name"].astype(str).str.replace(r'/\d+$', '').astype(int)

但是,在此之前,我想完全删除包含字母 (A-Z) 的行。

我试过了:

df[~df["column name"].str.lower().str.startswith('A-Z')]

我还尝试了其他一些表达式,但是没有清理数据。

DataFrame 看起来像这样:

          A         B         C
0       8161       0454   9600
1 -     3780       1773   1450
2       2564       0548   5060
3       1332       9179   2040
4       6010       3263   1050
5   I Forgot       7849   1400/10000

Col C - 1400/10000 - 我写的第一个表达式只是删除了“/ 10000”并保持为“1400”

现在我需要删除“A5”中的单词表达

【问题讨论】:

  • 您愿意分享您的数据样本吗?

标签: python regex pandas dataframe


【解决方案1】:

使用正则表达式,您可以为所有包含 [a-z] 之间字符的行创建掩码。然后你可以删除这些行。像这样:

mask = df['a'].str.lower().str.contains("[a-z]")
idx = df.index[mask]
df = df.drop(idx, axis=0)

【讨论】:

    猜你喜欢
    • 2022-08-11
    • 2017-03-18
    • 2021-10-13
    • 2014-04-16
    • 2018-02-25
    • 2016-08-07
    • 1970-01-01
    相关资源
    最近更新 更多