1.修改单列的数据类型

import pandas as pd
import numpy as np

df = pd.read_csv('test.csv')
df['column_name'] = df['column_name'].astype(np.str)
import pandas as pd
import numpy as np

df = pd.read_csv('test.csv')
df['column_name'] = df['column_name'].astype(np.str)
print(df.dtypes)

2.修改指定多列的数据类型

import pandas as pd

df[['c3','c5']] = df[['c3','c5']].apply(pd.to_numeric)
import pandas as pd

df[['c3','c5']] = df[['c3','c5']].apply(pd.to_numeric)
print(df.dtypes)

3.创建dataframe时,修改数据类型

import pandas as pd

# method1
df = pd.DataFrame(data, dtype='float')
print(df.dtypes)

# method2
df = pd.DataFrame(data, dtype=np.float64)
import pandas as pd

# method1
df = pd.DataFrame(data, dtype='float')
print(df.dtypes)

# method2
df = pd.DataFrame(data, dtype=np.float64)
print(df.dtypes)

4.读取时,修改数据类型

import pandas as pd

df = pd.read_csv("somefile.csv", dtype = {'column_name' : str})

df = pd.DataFrame(data, dtype='float')

df = pd.DataFrame(data, dtype=np.float64)
import pandas as pd

df = pd.read_csv("somefile.csv", dtype = {'column_name' : str})

df = pd.DataFrame(data, dtype='float')

df = pd.DataFrame(data, dtype=np.float64)
print(df.dtypes)

5.自动

import pandas as pd

df = df.infer_objects()
import pandas as pd

df = df.infer_objects()
print(df.dtypes)