數(shù)據(jù)分析Pandas庫應用

讀入輸出

import pandas as pd
people=pd.read_excel('*.xlsx') #讀入excel
people.columns=['ID','','','',''] #設置列名
people.set_index('ID',inplace=True)#設置ID作為參考指標數(shù)
people.to_excel('*.xlsx')

Series使用——輸出table

import pandas as pd

s1=pd.Series([1,2,3],index=[1,2,3],name='A')
s2=pd.Series([10,20,30],index=[1,2,3],name='B')
s3=pd.Series([100,200,300],index=[1,2,3],name='C')
df=pd.DataFrame({s1.name:s1,s2.name:s2,s3.name:s3})
#index有對齊關系
print(df)

單元格數(shù)據(jù)運算

#方法一
books['Price']=books['ListPrice']*books['Discount']  #重載,單元格對應相乘
#方法二
for i in books.index:
  books['Price'].at[i]=books['ListPrice'].at[i]*books['Discount'].at[i] 

#apply() 用于間接調用函數(shù) 
books['ListPrice']=books['ListPrice'].apply(add_2)  

數(shù)據(jù)排序

products.sort_values(by=['Worthy','Price'],inplace=True,ascending=[True,False]) #按列為參考進行排序

條件篩選

students=students.loc[students.Age.apply(lambda a:18<=a<=30)].loc[students['Score'].apply(level_a)] 
#loc條件篩選

繪圖

#方法一
students.plot.bar(x='Field',y='Number',color='orange',title='international students by field')
#方法二
plt.bar(students.Field,students.Number)
plt.xticks(students.Field,rotation=90)
plt.xlabel('Field')
plt.ylabel('Number')
plt.title('International Students By Field',fontsize=16)
plt.tight_layout()
plt.show()

Vlookup匹配

table=students.join(scores,how='left').fillna(0)  #類似與vlookup的數(shù)據(jù)匹配

分割split

df=employees['Full Name'].str.split(expand=True)

簡易運算

temp=students[['Test_1','Test_2','Test_3']]
row_sum=temp.sum(axis=1) #從左到右求和
row_mean=temp.mean(axis=1)
students['Total']=row_sum
students['Average']=row_mean
col_mean=students[['Test_1','Test_2','Test_3','Total','Average']].mean()

去重

#方法一
students.drop_duplicates(subset='Name',inplace=True,keep='last') #去重
#方法二
dupe=students.duplicated(subset='Name')
dupe=dupe[dupe==True]
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容