在这里分享一些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]