【问题标题】:Pandas: How to remove non-alphanumeric columns in SeriesPandas:如何删除系列中的非字母数字列
【发布时间】:2020-02-25 12:44:28
【问题描述】:

熊猫系列可以包含无效值:

a     b     c     d      e      f     g 
1    ""   "a3"  np.nan  "\n"   "6"   " "
df = pd.DataFrame([{"a":1, "b":"", "c":"a3", "d":np.nan, "e":"\n", "f":"6", "g":" "}])
row = df.iloc[0]

我想生成一个干净的系列,只保留包含 数字值非空非仅空格字母数字字符串的列:

  • b 应该被删除,因为它是一个空字符串;
  • d 因为np.nan;
  • eg 因为只有空格的字符串。

预期结果:

a      c     f
1    "a3"   "6"

如何过滤包含数字或有效字母数字的列?

  • row.str.isalnum()a 返回 NaN,而不是我期望的 True。
  • row.astype(str).str.isalnum()dnp.nan 更改为字符串 "nan",随后将其视为有效字符串。
  • row.dropna() 当然只掉线 d (np.nan)。

我没有看到https://pandas.pydata.org/pandas-docs/stable/reference/series.html 列出的许多其他可能性

作为一种解决方法,我可以在 items() 上循环检查类型和内容,并根据我想要保留的值创建一个新系列,但这种方法效率低下(而且丑陋):

for index, value in row.items():
    print (index, value, type(value))


# a 1 <class 'numpy.int64'>
# b  <class 'str'>
# c a3 <class 'str'>
# d nan <class 'numpy.float64'>
# e 
#  <class 'str'>
# f 6 <class 'str'>
# g   <class 'str'>

是否有任何布尔过滤器可以帮助我挑选出好的列?

【问题讨论】:

    标签: python pandas dataframe series


    【解决方案1】:

    将值转换为字符串并通过Series.notna 与按位AND - &amp; 链接另一个掩码:

    row = row[row.astype(str).str.isalnum() & row.notna()]
    print (row)
    a     1
    c    a3
    f     6
    Name: 0, dtype: object
    

    【讨论】:

    • 完美,@jezrael。谢谢您的回答。我错过了清理np.nan.notna。对了,为什么要加.fillna(False)?条件row.astype(str).str.isalnum() 在没有...的情况下给出相同的结果
    【解决方案2】:

    你可以使用正则表达式

    row[row.notna() & row.astype(str).str.match('[a-zA-Z0-9]+')]
    

    【讨论】:

    • 在我的例子中,编码应该考虑到德语和东方国家语言的特殊字符,所以匹配字符串很容易变得非常复杂。还是谢谢你的回答。
    猜你喜欢
    • 2020-06-22
    • 1970-01-01
    • 2016-07-20
    • 2012-09-25
    • 2018-02-24
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多