i want convert string
value in pandas dataframe
float
, , can define short function this, it's not pythonic way that. dataframe looks this:
>>> df = pd.dataframe(np.array([['1', '2', '3'], ['4', '5', '6']])) >>> df 0 1 2 0 1 2 3 1 4 5 6 >>> df.dtypes 0 object 1 object 2 object dtype: object >>> type(df[0][0]) <type 'str'>
i wonder whether there built-in functions of pandas dataframe
convert string
value float
. if know built-in function on pandas doc, please post link.
assuming values can correctly converted float, can use dataframe.astype()
function convert type of complete dataframe float. example -
df = df.astype(float)
demo -
in [5]: df = pd.dataframe(np.array([['1', '2', '3'], ['4', '5', '6']])) in [6]: df.astype(float) out[6]: 0 1 2 0 1 2 3 1 4 5 6 in [7]: df = df.astype(float) in [8]: df.dtypes out[8]: 0 float64 1 float64 2 float64 dtype: object
.astype()
function has raise_on_error
argument (which defaults true) can set false
make ignore errors . in such cases, original value used in dataframe -
in [10]: df = pd.dataframe([['1', '2', '3'], ['4', '5', '6'],['blah','bloh','bleh']]) in [11]: df.astype(float,raise_on_error=false) out[11]: 0 1 2 0 1 2 3 1 4 5 6 2 blah bloh bleh
to convert series/column float, again assuming values can converted, can use [series.astype()][2]
. example -
df['somecol'] = df['somecol'].astype(<type>)
Comments
Post a Comment