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.
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]
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]
How to do reverse deadshot answer, i mean i want to float to string
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.
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]
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]
How to do reverse deadshot answer, i mean i want to float to string