Find Numeric Column Names in Pandas

I need to select columns in Pandas that 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 the first five columns. Sort of:

df[df.columns.isnumeric()]

EDIT

I came up with a solution:

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

not very pythonic or pandasian, but it works.

+4
source share
4 answers

Try

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     

EDIT: If you are interested in choosing column names that are numeric, here is what 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()]

You get

    0.0 1.0 2.0
0   1   3   7
1   2   4   8
+5
source

Here is the answer for the EDIT part:

I intentionally created a mixture of column names in the form of real numbers and strings that can be converted to numbers:

In [44]: df.columns.tolist()
Out[44]: [0, 1, 2, 3, '4', 'window_label', 'next_states', 'ids']
# NOTE:                ^

we can use the method pd.to_numeric(..., errors='coerce'):

In [41]: df.columns[pd.to_numeric(df.columns, errors='coerce').to_series().notnull()]
Out[41]: Index([0, 1, 2, 3, '4'], dtype='object')

In [42]: cols = df.columns[pd.to_numeric(df.columns, errors='coerce').to_series().notnull()]

In [43]: df[cols]
Out[43]:
      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
+1

-, . . float , , int float. :

import pandas as pd

df = pd.DataFrame({0: [17.0, 18, 16, 15, 15],
                   1: [18.0, 16, 15, 15, 16],
                   2.0: [16.0, 15, 15, 16, 15],
                   3: [15.0, 15, 16, 15, 17],
                   4: [15.0, 16, 15, 17, None],
                   'window_label': ['ddddd' for i in range(5)],
                   'next_states': ['d' for i in range(5)],
                   'ids': [13.0 for i in range(5)]})

num_cols = []
for col in df.columns.values:
    try:
        float(col)
        num_cols.append(col)
    except ValueError:
        pass

print(df[num_cols])

:

      0     1   2.0     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

Edit1: , / .

import pandas as pd


def is_num(cols):
    for col in cols:
        try:
            float(col)
            yield col
        except ValueError:
            continue

df = pd.DataFrame({0: [17.0, 18, 16, 15, 15],
                   1: [18.0, 16, 15, 15, 16],
                   2.0: [16.0, 15, 15, 16, 15],
                   3: [15.0, 15, 16, 15, 17],
                   4: [15.0, 16, 15, 17, None],
                   'window_label': ['ddddd' for i in range(5)],
                   'next_states': ['d' for i in range(5)],
                   'ids': [13.0 for i in range(5)]})

print(df[[col for col in is_num(df.columns.values)]])

, , .

+1

, , :

df.columns[df.columns.str.isnumeric()]

df.iloc[:,df.columns.str.isnumeric()]
0

Source: https://habr.com/ru/post/1676857/


All Articles