gpt4 book ai didi

python-3.x - 获取 pd.DataFrame 中的所有 str 类型元素

转载 作者:行者123 更新时间:2023-12-04 22:40:01 25 4
gpt4 key购买 nike

基于我对 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 = 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 s:
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']

关于python-3.x - 获取 pd.DataFrame 中的所有 str 类型元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49745540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com