1蛤吓、引入pandas
import pandas as pd
讀取excel
df=pd.read_excel('1.xlsx')
寫出到excel(文件名相同將會(huì)覆蓋)
df.to_excel('1.xlsx')
數(shù)據(jù)排序
newDF = df.sort(['曝光量', '帶來的訪客數(shù)'], ascending=[True, False]); #多重排序
使用&(并)與| (或)實(shí)現(xiàn)多條件篩選
df[df['id']>100 & df['id']<200]
#in篩選方式
df[df['id'].isin([100,101,102])]
獲取行數(shù)和列數(shù)
df.shape[0]
df.shape[1]
數(shù)據(jù)清洗
misc['product_desc'] = misc['product_desc'].str.replace('\n', '')
df["Make"] = df["Make"].map(str.strip)
按照某列刪除重復(fù)項(xiàng)
df = df.drop_duplicates('b')
刪除空行/列
import numpy as np
df['測試列']=np.nan #這里增加一列模擬數(shù)據(jù)
df.dropna(axis=1,how='all')
#axis為0和1分別代表按行和列爹殊,how='all' 或者'any' 則表示是正行/列數(shù)據(jù)全部為Nan或者是只要任一出現(xiàn)Nan進(jìn)行刪除
重置索引列
ndf=df[df['標(biāo)題']=='空間']
ndf.head()
#=================數(shù)據(jù)如下=================
ID 標(biāo)題 正文
8 500002 空間 空間百分之八十滿意吧拘悦,反正比老款的好多了
18 500003 空間 車間方面表現(xiàn)也很不錯(cuò)星著,儲(chǔ)物空間也足夠用
假如我們像正常的操作df
for i in range(ndf.shape[0]):
print(ndf.ix[i,0])
這里將會(huì)得到類似下面的報(bào)錯(cuò):
File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)
File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)
File "pandas\hashtable.pyx", line 303, in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:6610)
File "pandas\hashtable.pyx", line 309, in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:6554)
解決的方法就是使用reset_index重置索引即可
ndf.reset_index(drop=True) #不加drop選項(xiàng)的話則新增一列索引