Python:Pandas 根据字符串长度过滤字符串数据 [英] Python: Pandas filter string data based on its string length

查看:31
本文介绍了Python:Pandas 根据字符串长度过滤字符串数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢过滤掉字符串长度不等于10的数据.

I like to filter out data whose string length is not equal to 10.

如果我尝试过滤掉 A 列或 B 列的字符串长度不等于 10 的任何行,我会尝试这样做.

If I try to filter out any row whose column A's or B's string length is not equal to 10, I tried this.

df=pd.read_csv('filex.csv')
df.A=df.A.apply(lambda x: x if len(x)== 10 else np.nan)
df.B=df.B.apply(lambda x: x if len(x)== 10 else np.nan)
df=df.dropna(subset=['A','B'], how='any')

这运行缓慢,但正在运行.

This works slow, but is working.

但是,当A中的数据不是字符串而是数字(read_csv读取输入文件时解释为数字)时,有时会出错.

However, it sometimes produce error when the data in A is not a string but a number (interpreted as a number when read_csv read the input file).

  File "<stdin>", line 1, in <lambda>
TypeError: object of type 'float' has no len()

我认为应该有更高效、更优雅的代码而不是这个.

I believe there should be more efficient and elegant code instead of this.

根据下面的回答和评论,我找到的最简单的解决方案是:

Based on the answers and comments below, the simplest solution I found are:

df=df[df.A.apply(lambda x: len(str(x))==10]
df=df[df.B.apply(lambda x: len(str(x))==10]

df=df[(df.A.apply(lambda x: len(str(x))==10) & (df.B.apply(lambda x: len(str(x))==10)]

df=df[(df.A.astype(str).str.len()==10) & (df.B.astype(str).str.len()==10)]

推荐答案

import pandas as pd

df = pd.read_csv('filex.csv')
df['A'] = df['A'].astype('str')
df['B'] = df['B'].astype('str')
mask = (df['A'].str.len() == 10) & (df['B'].str.len() == 10)
df = df.loc[mask]
print(df)

应用于filex.csv:

Applied to filex.csv:

A,B
123,abc
1234,abcd
1234567890,abcdefghij

上面的代码打印

            A           B
2  1234567890  abcdefghij

这篇关于Python:Pandas 根据字符串长度过滤字符串数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆