Currently I can create a list of conversion functions like the following:
casts = [float, float, int, str, int, str, str]
but I would like to do it in the following manner:
casts = input("Enter the casts: ") # this would be str str int int float
I tried just doing cast.split()
but that only outputs a list of strings and not the conversion functions.
How would I go about achieving my objective?
3
A function is not a name. The blessed way is to use a dictionary to map names to functions:
casts={'int': int, 'float': float, 'str': str}
cast = casts[input('Enter the cast name')]
An anti-pattern allows to search for names in a module:
import builtins
cast = getattr(builtins, input('Enter the cast name)]
But beware, although it is allowed by the language, this breaks the separation between the user code and the internals of the language. You should avoid it if you can…
From your comments, what you are looking for is something close to:
cast_ref = {'int': int, 'float': float, 'str': str}
casts = [cast_ref[src] for src in input('Enter the casts: ').split()]
6
If you don’t know the data types ahead of time, you can use pandas’ built-in data type inference mechanisms to automatically detect the data types of each column.
import pandas as pd
# Read the data file into a pandas DataFrame
df = pd.read_csv('data.csv')
# Infer data types for each column
df = df.infer_objects()
# Print the resulting DataFrame
print(df)
casts = [float, float, int, str, int, str, str]
def tonumtype(item,num)
tonumb = f"""
{item}({num}) """
return eval(tonumb)
tonumtype(casts[1],10) = float(10)
1