如何在数据框中找到也包含Null值的数字列?

Vam*_*shi 7 python dataframe python-3.x pandas

数据框如下所示:

          col1  col2   col3    col4    col5    col6    col7
points                                                    
x1         0.6  '0'   'first'  0.93   'lion'   0.34   0.98
x2         0.7  '1'  'second'  0.47    'cat'   0.43   0.76
x3         NaN  '0'   'third'  0.87  'tiger'   0.24   0.10
x4         0.6  '0'   'first'  0.93   'lion'   0.34   0.98
x5         0.5  '1'   'first'  0.32     NaN    0.09   NaN
x6         0.4  '0'   'third'  0.78  'tiger'   0.18   0.17
x7         0.5  '1'  'second'  0.98    'cat'   0.47   0.78 

numeric=df.select_dtypes(include=["number"])
others=df.select_dtypes(exclude=["number"])
print(numeric)

output:
          col4   col6
points                                                    
x1        0.93   0.34
x2        0.47   0.43   
x3        0.87   0.24   
x4        0.93   0.34   
x5        0.32   0.09   
x6        0.78   0.18   
x7        0.98   0.47   
Run Code Online (Sandbox Code Playgroud)

但我需要输出如下:

          col1  col4    col6    col7
points                                                    
x1         0.6  0.93    0.34   0.98
x2         0.7  0.47    0.43   0.76
x3         NaN  0.87    0.24   0.10
x4         0.6  0.93    0.34   0.98
x5         0.5  0.32    0.09   NaN
x6         0.4  0.78    0.18   0.17
x7         0.5  0.98    0.47   0.78 
Run Code Online (Sandbox Code Playgroud)

我知道NaN被视为Object并且这些列正被移动others.如何根据列中的值检测列?

jpp*_*jpp 1

你的问题归结为:

如何转换本来是数字但当前具有objectdtype 的列。

一旦这个问题得到解决,pd.DataFrame.select_dtypes将按预期工作。这意味着您事先不知道哪个系列应该是数字。但是您可以尝试将列转换为当前具有objectdtype 的数字。如果发现任何非空值,则可以应用转换。

for col in df.select_dtypes(include=['object']):
    s = pd.to_numeric(df[col], errors='coerce')
    if s.notnull().any():
        df[col] = s

print(df.dtypes)

points     object
col1      float64
col2       object
col3       object
col4      float64
col5       object
col6      float64
col7      float64
dtype: object
Run Code Online (Sandbox Code Playgroud)

该逻辑适用于您提供的数据。例如,当您有一系列主要是字符串和一些数字时,它就不起作用。在这种情况下,您将需要定义更精确的逻辑来确定哪个系列应被视为数字。