Change columns names from string to float

Question:

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.

Asked By: Reut

||

Answers:

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]
Answered By: jezrael

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]
Answered By: deadshot

How to do reverse deadshot answer, i mean i want to float to string

Answered By: Hakan Güneş
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.