在 pandas 中找到数字列名称 [英] find numeric column names in Pandas

查看:51
本文介绍了在 pandas 中找到数字列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Pandas中选择仅包含列名称中数值的列,例如:

I need to select columns in Pandas which contain only numeric values in column names, for example:

df=
          0     1     2     3     4 window_label next_states       ids
0      17.0  18.0  16.0  15.0  15.0        ddddd           d      13.0
1      18.0  16.0  15.0  15.0  16.0        ddddd           d      13.0
2      16.0  15.0  15.0  16.0  15.0        ddddd           d      13.0
3      15.0  15.0  16.0  15.0  17.0        ddddd           d      13.0
4      15.0  16.0  15.0  17.0   NaN        ddddd           d      13.0

所以我只需要选择前五列。像这样的东西:

so I need to select only first five columns. Something like:

df[df.columns.isnumeric()]

编辑

我想出了解决方案:

digit_column_names = [num for num in list(df.columns) if isinstance(num, (int,float))]
df_new = df[digit_column_names]

不是很Python或pandasian,但可以。

not very pythonic or pandasian, but it works.

推荐答案

尝试

df.ids = df.ids.astype('object')    
new_df = df.select_dtypes([np.number])


    0       1       2       3       4       
0   17.0    18.0    16.0    15.0    15.0    
1   18.0    16.0    15.0    15.0    16.0    
2   16.0    15.0    15.0    16.0    15.0    
3   15.0    15.0    16.0    15.0    17.0    
4   15.0    16.0    15.0    17.0    NaN     

编辑:
如果您有兴趣选择数字列名,则可以使用以下内容

If you are interested in selecting column names that are numeric, here is something that you can do.

df = pd.DataFrame({0: [1,2], '1': [3,4], 'blah': [5,6], 2: [7,8]})
df.columns = pd.to_numeric(df.columns, errors = 'coerce')
df[df.columns.dropna()]

您得到

    0.0 1.0 2.0
0   1   3   7
1   2   4   8

这篇关于在 pandas 中找到数字列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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