Method # 1: Using Output: Output: Method # 2: Using Output: Output: Latest questions # import pandas as pd
import
pandas as pd
# sample data frame
df
=
pd.DataFrame ({
’A’
: [
1
,
2
,
3
,
4
,
5
],
’B’
: [
’a’
,
’b’
,
’ c’
,
’d’
,
’ e’
],
’C’
: [
1.1
,
’1.0’
,
’1.3’
,
2
,
5
]})
# convert all columns to string
df
=
df.astype (
str
)
print
(df.dtypes)
# import pandas as pd
import
pandas as pd
# sample data frame
df
=
pd.DataFrame ({
’ A’
: [
1
,
2
,
3
,
4
,
5
],
’B’
: [
’a’
,
’ b’
,
’c’
,
’ d’
,
’e’
],
’C’
: [
1.1
,
’1.0’
,
’ 1.3’
,
2
,
5
]})
# using a dictionary to convert specific columns
convert_dict
=
{
’A’
:
int
,
’C’
:
float
}
df
=
df.astype ( convert_dict)
print
(df.dtypes)
# import pandas as pd
import
pandas as pd
# sample data frame
df
=
pd.DataFrame ({
’ A’
: [
1
,
2
,
3
,
’4’
,
’5’
],
’ B’
: [
’a’
,
’b’
,
’ c’
,
’d’
,
’ e’
],
’C’
: [
< code class = "value"> 1.1 ,
’2.1’
,
3.0
,
’4.1’
,
’ 5.1’
]})
# using the apply method
df [[
’A’
,
’ C’
]]
=
df [[
’A’
,
’C’
]].
apply
(pd.to_numeric)
print
(df.dtypes)
This method attempts to gently convert by inferring the data type of the object type columns. Non-object and non-reversible columns remain unchanged.
# import pandas as pd
import
pandas as pd
# sample data frame
df
=
pd.DataFrame ({
’A’
: [
1
,
2
,
3
,
4
,
5
],
’B’
: [
’ a’
,
’b’
,
’c’
,
’d’
,
’ e’
],
’C’
: [
1.1
,
2.1
,
3.0
,
4.1
,
5.1
]
}, dtype
=
’object’
)
# data type conversion х
df
=
df.infer_objects ( )
print
(df.dtypes)
Shop
Wiki