在這裏分享一些pandas基礎的語法,這是我整理的部分內容。後面持續更新!!!
#!/usr/bin/env python
# coding: utf-8
#!/usr/bin/python
# -*- coding: UTF-8 -*
"""
@author:li-boss
@file_name: pandas_one.py
@create date: 2019-11-01 22:13
@blog https://leezhonglin.github.io
@csdn https://blog.csdn.net/qq_33196814
@file_description:
"""
# In[1]:
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
# In[2]:
# 讀取包含多層級索引的excel,使用header參數
# header = [index1,index2...] 多層級使用,index1..index2表示多級索引的行
# header = None 無列標籤時使用
pd.read_excel('業務表.xlsx',header=[0,1])
# In[5]:
# sheet_name 用於指定表格當中sheet的編號,0表示sheet1,1表示sheet2。。。
# index_col 表示以哪一列作爲行索引
sheet2 = pd.read_excel('業務表.xlsx',sheet_name=1,header=None,index_col=0)
sheet2
# In[20]:
# 設置某一列爲行索引
# sheet2.set_index(0)
# 把行索引設置爲新的列
# sheet2.reset_index()
# In[6]:
column = pd.MultiIndex.from_product([['上半年','下半年'],['90#','93#','97#']])
# In[7]:
# 使用dataFrame的columns屬性,來對錶格索引重新賦值
sheet2.columns = column
sheet2
# In[17]:
# 多級索引的賦值使用如下方法
sheet2.loc['成都',('上半年','90#')] = 8900
# In[28]:
# 多級索引的訪問可以使用如下方法
# 這種屬於跨級訪問,相當於對sheet2['上半年']產生的臨時對象賦值
sheet2['上半年'].loc['成都','90#'] = 18000
# In[24]:
# 多級索引賦值還可以採用如下辦法
sheet2_copy = sheet2['上半年'].copy()
sheet2_copy.loc['成都','90#'] = 9700
sheet2['上半年'] = sheet2_copy
sheet2
# In[28]:
# 普通一級索引的訪問方式回顧
sheet2_copy
# In[33]:
# 顯式訪問
# 1. 訪問元素
sheet2_copy.loc['綿陽']['97#']
sheet2_copy['97#'].loc['綿陽']
sheet2_copy.loc['綿陽','97#']
# 2. 訪問行
sheet2_copy.loc['行索引']
sheet2_copy.loc[index1:index2]
# 3. 訪問列
sheet2_copy['列索引']
sheet2_copy.loc[:,column1:column2]
# In[36]:
# dataframe的列切片要從行的方向着手
sheet2_copy.loc[:,'93#':'97#']
# In[39]:
sheet2_copy.loc['成都':'汶川','90#':'97#']
# In[41]:
# 隱式訪問
# 1.訪問元素
# sheet2_copy.iloc[indexnumber,columnnumber]
# 2.訪問行、行切片
sheet2_copy.iloc[0]
sheet2_copy.iloc[0:2]
# 3.訪問列、列切片
sheet2_copy.iloc[:,0]
sheet2_copy.iloc[:,0:2]