Python 3.x 获取pd.DataFrame中的所有str类型元素
基于我对熊猫的一点了解,Python 3.x 获取pd.DataFrame中的所有str类型元素,python-3.x,pandas,Python 3.x,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','th
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']
您可以使用str.isdigit
和取消堆栈
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'}
如果使用,也可以省略浮点数。有两种可能的方法-检查是否保存为字符串的数值 检查差异:
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']
如果需要将所有值保存为字符串,请使用:
如果您严格地看什么是字符串值,而性能不是一个问题,那么这是一个非常简单的答案
df.where(df.applymap(type).eq(str)).stack().tolist()
['a', 'c', '+', 'this is']
这是最好的办法,,IMHO@AmiTavory-谢谢。这是elegence。我使用了
df.apply(lambda x:pd.to_numeric(x,errors='ignore'))
将str numeric(如'1.23'
转换为1.23
),因此我可以告诉您的函数在这个示例中可以工作。但是如果数据框中有列表元素,则np.unique()
可能会失败。“我会投你一票的。”加维——谢谢你np.unique
应该省略,这是不必要的。@jezrael好吧,我设置了errors=ignore
,目的是先将'1.23'
转换为1.23
,这与这个问题无关。在那之后,我意识到有必要浏览一下数据框中还包含哪些类型的str。很高兴看到你回答问题(-:@piRSquared!你的销售代表已经成长了很多!
s = df.stack()
L = s[s.apply(lambda x: isinstance(x, str))].unique().tolist()
print (L)
['2.78', 'a', '3', 'c', '+', 'this is']
df.where(df.applymap(type).eq(str)).stack().tolist()
['a', 'c', '+', 'this is']