Pandas type
Usage 1: Modify the data type of a column
df: pd.DataFrame = pd.DataFrame([
['a', '1', '4.2'],
['b', '70', '0.03'],
['x', '5', '0']
], columns=['one', 'two', 'three'])
df['two'] = df['two'].astype('int64') # 修改'two'列为 int类型
one | two | three |
---|---|---|
a | 1 | 4.2 |
b | 70 | 0.03 |
c | 5 | 0 |
Usage 2: Modify the data type of multiple columns
df: pd.DataFrame = pd.DataFrame([
['a', '1', '4.2'],
['b', '70', '0.03'],
['x', '5', '0']
], columns=['one', 'two', 'three'])
df[['two', 'three']] = df[['two', 'three']].apply(pd.to_numeric) # 内置函数,to_numeric() 可以将一列转换为数值类型,自动判断是 int 还是 float
Similar built-in functions also include:, pd.to_datetime()
conversion to datetime type, and pd.to_timedelta()
conversion to timestamp type