【Python】pandas模块中更改Series的数据类型
今天我們主要解決以下實(shí)際問(wèn)題:一份黑名單數(shù)據(jù)存儲(chǔ)在excel中,由于數(shù)據(jù)量龐大,現(xiàn)需要通過(guò)pandas找到某一列的重復(fù)數(shù)據(jù),處理后再存入到excel中。
pandas 是基于NumPy 的一種工具,該工具是為了解決數(shù)據(jù)分析任務(wù)而創(chuàng)建的,主要數(shù)據(jù)結(jié)構(gòu)為兩個(gè)類:
DataFrame: 可以理解為表格,類似于Excel的表格 pandas.core.frame.DataFrame
Series: 表示單列。DataFrame包含多個(gè)列,即多個(gè)Series,每個(gè)Series都有名稱。pandas.core.series.Series
Pandas所支持的數(shù)據(jù)類型(dtype):?
1. float?(float64)
2. int?(int64,uint64)
3. bool?
4. datetime64[ns]? (2013-01-02)
5. datetime64[ns, tz]?
6. timedelta[ns]?
7. category?
8. object?(字符串)
默認(rèn)的數(shù)據(jù)類型是int64,float64
以下是原始的excel文件
先查看文件中Series每一列的數(shù)據(jù)類型
import pandas as pd# 更改數(shù)據(jù)類型 def change_data_type():print(excel_df.dtypes)if __name__ == '__main__':excel_df = pd.read_excel('E:\zenglingwei\\test\\5.xlsx')change_data_type()我們發(fā)現(xiàn)blacklistValue默認(rèn)是int類型,但我們知道身份證18位,再次存入excel中時(shí)后面幾位會(huì)變成0,所以我們需要對(duì)這列進(jìn)行數(shù)據(jù)類型轉(zhuǎn)換。主要有兩種思路,一種是讀取excel時(shí)轉(zhuǎn)換,另外一種是讀取后轉(zhuǎn)換。
一、讀取時(shí)全部轉(zhuǎn)換為字符串,dtype='object'或者dtype='str'
import pandas as pd# 更改數(shù)據(jù)類型 def change_data_type():print(excel_df.dtypes)if __name__ == '__main__':excel_df = pd.read_excel('E:\zenglingwei\\test\\5.xlsx',dtype='object') # dtype='str'change_data_type()二、讀取時(shí)指定列轉(zhuǎn)換為字符串,object或者str
# 更改數(shù)據(jù)類型 def change_data_type():print(excel_df.dtypes)if __name__ == '__main__':excel_df = pd.read_excel('E:\zenglingwei\\test\\5.xlsx',dtype = {'blacklistValue' : object,'priority':str}) # dtype='str'change_data_type()三、讀取后轉(zhuǎn)換為字符串:?astype(str),不可以使用astype(object)-->存入到excel時(shí)還是int類型。
import pandas as pd# 更改數(shù)據(jù)類型 def change_data_type():excel_df[['blacklistValue','priority']] = excel_df[['blacklistValue','priority']].astype(str)print(excel_df.dtypes)excel_df.to_excel('excel_to_python.xls',sheet_name='sheet', index=False)if __name__ == '__main__':excel_df = pd.read_excel('E:\zenglingwei\\test\\5.xlsx') # dtype='str'change_data_type() 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的【Python】pandas模块中更改Series的数据类型的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: react实现全选和反选_全选的实现
- 下一篇: 【Jmeter篇】jmeter Ant