Reut
Reut

Reputation: 1592

Change columns names from string to float

I have dataframe with many columns, some of them are strings and some are numbers. Right now when I print the columns names as list I get something like this:

df.columns.tolist()
>>>['name','code','date','401.2','405.6','507.3'...]

I would like to get the numerical columns as float numbers and not as string, I haven't found yet any way to do that, is is possible to do something like this? my goal in the end is to be able to create list only of the numerical columns names, so if you know other way to seperate them now when they are string could work also.

Upvotes: 2

Views: 1574

Answers (2)

deadshot
deadshot

Reputation: 9071

Using list comprehension

df.columns = [float(col) if col.replace('.', '').isnumeric() else col for col in df.columns]
res = df.columns.to_list()
print(res)

Output:

['name', 'code', 'date', 401.2, 405.6, 507.3]

Upvotes: 2

jezrael
jezrael

Reputation: 863731

Use custom function with try-except statement:

df = pd.DataFrame(columns=['name','code','date','401.2','405.6','507.3'])

def f(x):
    try:
        return float(x)
    except:
        return x

df.columns = df.columns.map(f)
 
print (df.columns.tolist())
['name', 'code', 'date', 401.2, 405.6, 507.3]

Upvotes: 2

Related Questions