6 pandas
处理字符串 时间序列等非数值信息
常用数据类型
- series 一维 带标签数组
- dataframe 二维数组
6.1 series
本质由两部分构成: 键(索引)+ 值
pd.Series([1,2,3,4],index=list('abcd'))
temp_dict = {'name':'hhh','age':'12'}
t1 = pd.Series(temp_dict)
a = {sring.ascii_uppercase[i]:i for i in fange(10)}
t2 = pd.Series(a)
t3 = pd.Series(a,index=list(sring.ascii_uppercase[5:15])) # 没有值的部分 默认为nan
# 也可以用astype()指定类型
切片和索引
几种常用方法如下
t[233]
t[2:10:2] # 首:尾:步长
t[t>4]
t['F']
len(t3.index)
list(t3.index)
len(t3.value)
一些方法和numpy不同,具体的可以查看官方文档
读取外部数据
比numpy要简单很多
import pandas as pd
# pandas 读取csv中的文件
df = pd.read_csv('./names.csv') # pd.read还有很多方法
print(df)
6.2 dataframe
构建
方法一
t = pd.Dataframe(np.arange(12).reshape(3,4))
'''
# 0 1 2 3
# 0 0 1 2 3
# 1 4 5 6 7
# 2 8 9 10 11
# index行索引 0轴 axis=0
# columns列索引 1轴 axis=1
'''
t1 = pd.Dataframe(np.arange(12).reshape(3,4), index=list('abc'),columns=list('WXYZ'))
方法二
字典法
temp_dict = {'name':['hhh','xxx'],'age':['12','13']}
t1 = pd.Dataframe(temp_dict)
# 若某些位置值缺失,为nan
读取
import pandas as pd
from pymongo import MongoClient
client = MongoClient()
collection = client['douban']['tv']
data = list(collection.find()
df = Dataframe(data)
print(df)
# 取行/取列
# - 方括号写数组,表示取行 进行行操作
# - 方括号写字符串,表示取列 进行列操作
df[:20]
df['Row_Labels'] # 这列为series类型,要取2列为dataframe
# 同时取行列
# 1. 标签索引数据
t.loc['a','Z'] # a行Z列(一个值)
t.loc['a'] # a行
t.loc[:,'Z'] # Z列
t.loc[:,['Z','X']] # 多行多列
# 2. 位置索引数据
t.loc[1,:] # 第2行
t.loc[:2] # 第3行
t.loc[[0,2],[2,1]] # 第1列到第3行^第3列、第2列(交点)
t.loc[:,['Z','X']] # 多行多列
基础属性和方法
t.index
t.columns
t.values
t.shape
t.dtypes
t.ndim # 维度
t.head(n) # 显示前n行 默认为前5行
t.info() # 展示概览
t.describe() # 只有数字类型才有的,展示统计数据(均值、中位数等)
# pd中的排序方法
pd.sort_values(by='',ascending=False) # 按xx进行排序,看函数定义 降序
布尔索引
不同条件之间 需要使用 括号 分开
df[ (df['Row_Labels'].str.len()>4) & (df['Count_Names']>700) ]
# str.有很多方法
缺失值的处理
- NAN
# 将原数组转化为布尔类型
pd.isnull(t)
pd.notnull(t)
# 处理
# 1. 直接删掉
t1 = t[ pd.notnull(t['W']) ] # 只保留了:原数组中 W列≠NAN的 那一行
t.dropna(axis=0,how='all') # 行 都为nan删掉该行
t.dropna(axis=0,how='any') # 行 有nan就删掉该行
t.dropna(axis=0,how='any',inplace=True) # 原地修改,和赋值的效果一样的
# 2. 填充数据
t.fillna(100)
t.fillna(t.mean())
t['age'].fillna( t['age'].mean() ) # 对某列操作
pandas算数据的时候 NAN不参与计算,和numpy不同
pandas读字符串的时候 会把NAN当成空,和numpy不同
# 注:NAN不参与计算,如 [10 nan 20]
# 是 arg = (10+20)/2 而不是 (10+0+20)/3
# 所以!
# 3. 处理为0的数据
t[t==0] = np.nan
# 使用场合:当前0是数据缺失的位置,这样才不会破坏数据的真实性
6.3 统计方法和字符串离散化
# coding=utf-8
import pandas as pd
from matplotlib import pyplot as plt
file_path = "./IMDB-Movie-Data.csv"
# 基本信息
df = pd.read_csv(file_path)
# print(df.head(1))
# print(df.info())
#rating,runtime分布情况
#选择图形,直方图
#准备数据
runtime_data = df["Rating"].values
max_runtime = runtime_data.max()
min_runtime = runtime_data.min()
#计算组数
print(max_runtime-min_runtime)
num_bin = (max_runtime-min_runtime)//0.5
#设置图形的大小
plt.figure(figsize=(20,8),dpi=80)
plt.hist(runtime_data,num_bin)
_x = [min_runtime]
i = min_runtime
while i<=max_runtime+0.5:
i = i+0.5
_x.append(i)
plt.xticks(_x)
plt.show()