获取 pd 中的所有 str 类型元素.数据帧



根据我对pandas的一点了解,pandas.Series.str.contains可以在pd.Series中搜索特定的str。但是,如果数据帧很大,而我只想在执行任何操作之前浏览其中的各种 str 元素,该怎么办?

像这样的例子:

pd.DataFrame({'x1':[1,2,3,'+'],'x2':[2,'a','c','this is']})
    x1  x2
0   1   2
1   2   a
2   3   c
3   +   this is

我需要一个函数来返回['+','a','c','this is']

如果您严格关注什么是字符串值并且性能不是问题,那么这是一个非常简单的答案。

df.where(df.applymap(type).eq(str)).stack().tolist()
['a', 'c', '+', 'this is']

有两种可能的方法 - 检查是否保存为字符串的数值。

检查差异:

df = pd.DataFrame({'x1':[1,'2.78','3','+'],'x2':[2.8,'a','c','this is'], 'x3':[1,4,5,4]}) 
print (df)
     x1       x2  x3
0     1      2.8   1
1  2.78        a   4 <-2.78 is float saved as string
2     3        c   5 <-3 is int saved as string
3     +  this is   4
#flatten all values
ar = df.values.ravel()
#errors='coerce' parameter in pd.to_numeric return NaNs for non numeric
L = np.unique(ar[np.isnan(pd.to_numeric(ar, errors='coerce'))]).tolist()
print (L)
['+', 'a', 'c', 'this is']

另一种解决方案是使用自定义函数检查是否可能转换为float

def is_not_float_try(str):
    try:
        float(str)
        return False
    except ValueError:
        return True
s = df.stack()
L = s[s.apply(is_not_float_try)].unique().tolist()
print (L)
['a', 'c', '+', 'this is']

如果需要,所有另存为字符串的值都使用 isinstance

s = df.stack()
L = s[s.apply(lambda x: isinstance(x, str))].unique().tolist()
print (L)
['2.78', 'a', '3', 'c', '+', 'this is']
您可以将

str.isdigitunstack一起使用

df[df.apply(lambda x : x.str.isdigit()).eq(0)].unstack().dropna().tolist()
Out[242]: ['+', 'a', 'c', 'this is']

使用正则表达式和集合联合,可以尝试类似

>>> set.union(*[set(df[c][~df[c].str.findall('[^d]+').isnull()].unique()) for c in df.columns])
{'+', 'a', 'c', 'this is'}

如果对数字使用正则表达式,也可以省略浮点数。

最新更新