pandas表格数据分析

pandas对表格类数据的处理,提供了两个重要的数据结构,Series和DataFrame。Series相当于map,DataFrame相当于表格。

Series

通过数组或map来构建Series。map的key为Series的index。

o = pd.Series([11,'32',True])
o = pd.Series({'x':10,'y':11})
# 通过index来获取值
o[['x','y']]
# 通过bool数组来删选值
o[o>0]
# 修改index
o.index = ['a','b']

DataFrame

构建

  • 字典
#等长列表的字典
# 以a,b为列 创建DataFrame
m = {'a':[1,2,3],'b':[2,3,4]}
p = pd.DataFrame(m)
# 以a,b为index 创建DataFrame
pd.DataFrame.from_dict(result,orient='index')

#嵌套字典
#外侧key 为列
m = {'a':{'1':2},'b':{'1':2}}
pd.DataFrame(m)
  • Series
    c = pd.DataFrame([a_series,b_series])
    
  • excel中读取 ```python

    读取excel的当前sheet页

    d = pd.read_excel(r”D:\code\br_mix_server\excel\common\ConfigValue.xlsx”,sheet_name=’任务’,skiprows=5)

    读取所有sheet页

    c = pd.concat(pd.read_excel(r’D:\code\br_mix_server\excel\common\ConfigValue.xlsx’,sheet_name=None))

得到excel所有的sheet names

d = pd.ExcelFile(r”D:\code\br_mix_server\excel\common\ConfigValue.xlsx”) d.sheet_names


## 基本操作

```python
# 每一列的类型
df.dtypes
# 列的重命名
df.columns=['date','name','address','area','prices']
# 遍历row
for index,row in df.iterrows():
    print(row['c1'], row['c2']) # 输出每一行
# 类型转换
df['b'] = pd.to_numeric(df['b'],errors='coerce')
df['Customer Number'].astype("int")

# 更改index inplace表示在原有df上修改,不新建
df.set_index(["Column"], inplace=True)

筛选表格

iloc , 基于index的整数索引。

# --------------- 对行的过滤
# 单行
df.iloc[0]
# 前两行
df[:2]
# 对行,列切片  iloc是int loc是str
df.iloc[0:1,1:2]
df.loc[:, 'max_speed'] = 30
# --------------- 对列的过滤
d[['B','C']]
d.B

生成布尔数组,并且根据bool数组来选择

# isin bb是id列表
data['副本ID'].isin(bb)


# 通过bool数组来选择row ,传入二维数组的话,Flase的会变为None
section[(section['话分类']=='PLAY') & (section['本话名称(地图显示)'] == sId)]
d[d['A']>10]

map

>>> s.apply(lambda x: x ** 2)
London      400
New York    441
Helsinki    144
dtype: int64

s.map('I am a {}'.format, na_action='ignore')

map和apply 有部分重叠,建议用apply。

处理表格数据

apply

DataFrame 的apply是对列或行进行操作,applymap是对每个元素操作

apply方法,可以对Seria和DataFrame使用


# 对name列进行处理,把处理结果新加一列
d2['code'] = d2['name'].apply(lambda x: int(''.join(filter(str.isdigit, x))))

字符操作

对Series有大量的字符操作

# 将字符按'|'分割成多列
x = x.str.split(pat='|',expand=True)
x.str.contans('x|y')

drop

  • 去掉指定name的行和列
  • 也有dropna,和drop_duplicate等,根据内容drop行
  • 更复杂的用选取操作过进行
# 删除项目  axis 1:columns 0:index
d2.drop(['key'],axis = 1)
d2.drop(columns = ['B','C'])
d2.dropna()
# row的内容一样会被删除
d2.drop_duplicates(Keep=False)
# 
c = c.replace('',np.nan)
c = c.dropna()

# 列的类型转换
data[c1] = pd.to_numeric(data[c1].str[0:-1])

层次化索引

# 对于层次化索引,先转换内层的
#stack:将数据的列转为行

# unstack:将数据的行旋转为列

合并表

可以整合数据,也可以对比两个数据的差异。DataFrame,Series都可以

# how 有三种模式,默认是inner,合并都有的key。left模式 没有一样key的时候保留左边表的记录,indicator 标记合并的key是否一边缺少
c = pd.merge(d,d2,on='key',how='left')
x = pd.merge(t1,t,left_on='剧本',right_on='所属小节(话)ID',how='right'indicator = True)

# 列一样,合并index
pd.concat([df1,df2])
# 比较两个表的差异 ,本身row没有重复的
pd.concat([df1,df2]).drop_duplicates(keep=False)

汇总和数据统计

Series针对数字的列表提供很多统计方法,包括sum,mean,std,count等。也有describe等复合统计。DataFrame基本也有这些方法,而且可以选择对index,还是对columns操作。对分组也可以指定多种聚合方法

Series指定多个统计方法 d2.agg([‘min’,’count’])

分组

grouped = df.groupby([8,12])
grouped.size().unstack(fill_value=0).to_csv('dd.csv')

# key为分组key,group为等于key的分组
for key,group in grouped:
    print(key)
    print(group)

grouped是一个GroupBy对象。实际上还没有进行任何计算,只是含有一些有关分组键的中间信息

分组聚合 agg

   Accepted combinations are:
    - function
    - string function name
    - list of functions and/or function names, e.g. ``[np.sum, 'mean']``
    - dict of axis labels -> functions, function names or list of such.

df.groupby('招录机关')['sum'].agg(['max','min'])
b = df.groupby('招录机关').agg({'sum':['max','min'],'名额':['sum']})

分段

# right = false,区间左边闭合
data['label'] =  pd.cut(data['成绩'],range(0,200,10),right=False)

画图

matplit默认字体不支持中文,可以在开头设置字体

import matplotlib.pyplot as plt
# 在我的 notebook 里,要设置下面两行才能显示中文
plt.rcParams['font.family'] = ['sans-serif']
# 如果是在 PyCharm 里,只要下面一行,上面的一行可以删除
plt.rcParams['font.sans-serif'] = ['SimHei']
    The kind of plot to produce:
    - 'line' : line plot (default)
    - 'bar' : vertical bar plot
    - 'barh' : horizontal bar plot
    - 'hist' : histogram
    - 'box' : boxplot
    - 'kde' : Kernel Density Estimation plot
    - 'density' : same as 'kde'
    - 'area' : area plot
    - 'pie' : pie plot
    - 'scatter' : scatter plot
    - 'hexbin' : hexbin plot.

s = pd.Series([1,23,4,6,9])
# 线性图
s.plot()
# 柱形图
s.plot(kind='bar',stacked=True)
# 柱形图
s.plot(kind='pie',autopct='%1.1f%%')
# 散列图

Updated: