dataframe中的數據類型及轉化


1 float與str的互化

 

import pandas as pd
import numpy as np

df = pd.DataFrame({'a':[1.22, 4.33],
                   'b':[3.44, 5.66]})
# 將float類型轉為str
# 法一
df['a'] = df['a'].apply(lambda x: str(x))
print(type(df['a'].values[1]))
# 法二
df['b'] = df['b'].astype(str)
print(type(df['b'].values[1]))
# str轉float同上
df['a'] = df['a'].apply(lambda x: float(x))
print(type(df['a'].values[1]))
df['b'] = df['b'].astype(float)
print(type(df['b'].values[1]))
# <class 'str'>
# <class 'str'>
# <class 'numpy.float64'>
# <class 'numpy.float64'>
View Code

2 建表時,如果賦的是空值,默認是float類型,所以要指定數據類型。

特別是建了空表后,與其它表融合時,要注意數據類型的改變。

df = pd.DataFrame({ 'a': [], 'b': [], }) print(df.info()) df = pd.DataFrame({ 'a': [], 'b': [], }, dtype = np.int64) print(df.info()) # <class 'pandas.core.frame.DataFrame'> # RangeIndex: 0 entries # Data columns (total 2 columns): # a 0 non-null float64 # b 0 non-null float64 # dtypes: float64(2) # memory usage: 76.0 bytes # None # <class 'pandas.core.frame.DataFrame'> # RangeIndex: 0 entries # Data columns (total 2 columns): # a 0 non-null int64 # b 0 non-null int64 # dtypes: int64(2) # memory usage: 76.0 bytes # None

參考:https://blog.csdn.net/jinruoyanxu/article/details/79150896


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM