一、基本数据结构
1. Series
能保存不同的数据类型的一维数组。
s=pd.Series([1,1.2,5.666])
print(s)
###
#0 1.000
#1 1.200
#2 5.666
#dtype: float64
(1)索引
默认是数字,可以使用index修改。
s=pd.Series([1,1.2,5.666],index=['a','b','c'])
print(s)
###
#a 1.000
#b 1.200
#c 5.666
#dtype: float64
s=pd.Series([1,1.2,5.666],index=['a','b','c'])
s.index=list('123')
print(s)
###
#1 1.000
#2 1.200
#3 5.666
#dtype: float64
查看索引
s=pd.Series([1,1.2,5.666],index=['a','b','c'])
print(s.index)
###
#Index(['a', 'b', 'c'], dtype='object')
索引取名
s=pd.Series([1,1.2,5.666],index=['a','b','c'])
s.index.name="字母"
print(s)
###
#字母
#a 1.000
#b 1.200
#c 5.666
#dtype: float64
(2)取值
s=pd.Series([1,1.2,5.666],index=['a','b','c'])
print(s.values)
print(s[1])
###
#[1. 1.2 5.666]
#1.2
s=pd.Series([1,1.2,5.666],index=['a','b','c'])
s.index=list('123')
print(s['2':])
###
#2 1.200
#3 5.666
#dtype: float64
(3)切片 同python
2. DataFrame
二维表格型数据结构。
先构造一组时间序列作为第一维的下标
date=pd.date_range('20240101',periods=6)
print(date)
###
#DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04',
# '2024-01-05', '2024-01-06'],
# dtype='datetime64[ns]', freq='D')
创建DataFrame结构
df=pd.DataFrame(np.random.randn(6,4))
print(df)
###
# 0 1 2 3
#0 0.886595 0.846141 -0.531918 0.322900
#1 -0.536548 0.481091 1.018595 1.026127
#2 0.206519 -0.514057 -0.701333 2.037837
#3 -0.442643 -1.070216 -3.135269 0.481431
#4 -0.999958 1.139363 0.604124 1.016186
#5 0.691995 1.478824 1.041788 0.675485
(1)索引
df=pd.DataFrame(np.random.randn(6,4),index=date,columns=list('abcd'))
print(df)
###
# a b c d
#2024-01-01 0.108157 0.190219 0.326589 0.236896
#2024-01-02 -0.240620 0.294782 -0.395887 -0.335942
#2024-01-03 -0.862676 -1.003561 0.094450 -0.584360
#2024-01-04 0.402737 2.188656 -0.769373 -0.970433
#2024-01-05 -1.243373 -0.110221 0.985069 0.002814
#2024-01-06 1.106766 0.350855 -0.574328 0.894795
(2)字典传入数据
df=pd.DataFrame({'a': 1, 'b': pd.Timestamp('20240101'),'c':pd.Series(1,index=list(range(4)),dtype=float),'d':np.array([3]*4,dtype=int),'e':pd.Categorical(["test","train","test","train"]),'f':'abc'})
print(df)
###
# a b c d e f
#0 1 2024-01-01 1.0 3 test abc
#1 1 2024-01-01 1.0 3 train abc
#2 1 2024-01-01 1.0 3 test abc
#3 1 2024-01-01 1.0 3 train abc
一个key为一列,其value是能够转化为Series的对象。
DataFrame要求每一列数据格式相同。
(3)查看数据
头尾数据
查看前后几行的数据,默认值为5。
print(df.head(1))
###
# a b c d e f
#0 1 2024-01-01 1.0 3 test abc
print(df.tail())
###
# a b c d e f
#0 1 2024-01-01 1.0 3 test abc
#1 1 2024-01-01 1.0 3 train abc
#2 1 2024-01-01 1.0 3 test abc
#3 1 2024-01-01 1.0 3 train abc
下标
print(df.index)
###
#Index([0, 1, 2, 3], dtype='int64')
列标
print(df.columns)
###
#Index(['a', 'b', 'c', 'd', 'e', 'f'], dtype='object')
数据
print(df.values)
###
#[[1 Timestamp('2024-01-01 00:00:00') 1.0 3 'test' 'abc']
# [1 Timestamp('2024-01-01 00:00:00') 1.0 3 'train' 'abc']
# [1 Timestamp('2024-01-01 00:00:00') 1.0 3 'test' 'abc']
# [1 Timestamp('2024-01-01 00:00:00') 1.0 3 'train' 'abc']]
(4)文件操作
文件读取
df=pd.read_csv("D:/files/WeChat Files/2023-11/test.CSV",encoding='gbk')
print(df.head(3))
###
# Unnamed: 0 MXXA50 M20E-FKS ... Unnamed: 109 Unnamed: 110 Unnamed: 111
#0 005804 km NaN NaN ... NaN NaN NaN
#1 NaN NaN NaN ... NaN NaN NaN
#2 LFMAP54K9NS000015 NaN NaN ... NaN NaN NaN
excel文件使用read_excel()
读取行列
#行读取
print(df.iloc[0:2])
###
# Sample Time Vehicle Speed Engine Speed ... Unnamed: 109 Unnamed: 110 Unnamed: 111
#0 MM:SS.mmm km/h rpm ... NaN NaN NaN
#1 00:00.0 0 803 ... 0.0 0.0 1.0
#
#[2 rows x 112 columns]
print(df.loc[0:2])
###
# Sample Time Vehicle Speed Engine Speed ... Unnamed: 109 Unnamed: 110 Unnamed: 111
#0 MM:SS.mmm km/h rpm ... NaN NaN NaN
#1 00:00.0 0 803 ... 0.0 0.0 1.0
#2 00:01.0 0 811 ... 0.0 0.0 1.0
#
#[3 rows x 112 columns]
#列读取
print(df['Sample Time'])
###
#0 MM:SS.mmm
#1 00:00.0
#2 00:01.0
#3 00:02.0
#4 00:03.0
# ...
#24199 42:31.2
#指定行
print(df['Sample Time'][:4])
###
#0 MM:SS.mmm
#1 00:00.0
#2 00:01.0
#3 00:02.0
#Name: Sample Time, dtype: object
#选多列
print(df[['Sample Time','Vehicle Speed']][:4])
###
# Sample Time Vehicle Speed
#0 MM:SS.mmm km/h
#1 00:00.0 0
#2 00:01.0 0
#3 00:02.0 0
添加行列
#添加下标为2的行
dit={'key1':'value1','key2':'value2'}
s=pd.Series(dit)
s.name=2
df=df._append(s)
#添加“序号”列
df=pd.read_csv("D:/files/WeChat Files/2023-11/test.CSV",encoding='gbk')
df['序号']=range(1,len(df)+1)
print(df.columns)
###
#Index(['Sample Time', 'Vehicle Speed', 'Engine Speed', 'Calculate Load',
# 'Vehicle Load', 'Mass Air Flow Sensor', 'Atmospheric Pressure',
# 'Unnamed: 109', 'Unnamed: 110', 'Unnamed: 111', '序号'],
# dtype='object', length=113)
删除行列
axis=0->行 axis=1->列 默认为0
#删除下标为1的行
#[2 rows x 112 columns]
df=df.drop([1])
print(df.head(2))
# Sample Time Vehicle Speed Engine Speed ... Unnamed: 109 Unnamed: 110 Unnamed: 111
#0 MM:SS.mmm km/h rpm ... NaN NaN NaN
#2 00:01.0 0 811 ... 0.0 0.0 1.0
#
#[2 rows x 112 columns]
#删除列
df=df.drop('Unnamed: 111',axis=1)
选择数据
指定行列
#df.loc[[index],[column]]
print(df.loc[[2, 3], ['Sample Time', 'Vehicle Speed']])
###
# Sample Time Vehicle Speed
#2 00:01.0 0
#3 00:02.0 0
条件选择
条件取交集(&)并集(|)
#返回布尔类型
print(df['Vehicle Speed']==0)
###
#0 False
#1 False
#2 False
#3 False
#4 False
#Name: Vehicle Speed, Length: 24204, dtype: bool
print(df[(df['Vehicle Speed']==0)&(df['Unnamed: 111']!=1.0)])
###
#Empty DataFrame
#Columns: [Sample Time, Vehicle Speed, Engine Speed, ...]
#Index: []
#
#[0 rows x 112 columns]
缺失值或异常值处理
方法 | 说明 |
dropna | 删除缺失值 |
fillna | 填充缺失值 |
isnull | 判断是否缺失值,返回布尔类型 |
notnull | 与上面方法相反 |
判断缺失值
print(df['Vehicle Speed'].isnull)
###
#<bound method Series.isnull of 0 km/h
#1 False
#2 False
#3 False
Name: Vehicle Speed, Length: 24204, dtype: bool
print(df['Vehicle Speed'].notnull())
###
#0 True
#1 True
#2 True
#3 True
Name: Vehicle Speed, Length: 24204, dtype: bool
填充缺失值
#使用nan替换'Vehicle Speed'中的缺失值
print(df['Vehicle Speed'].fillna('nan'))
可使用np.mean()计算平均值
inplace=True 在原始数据中进行修改
删除缺失值
df.dropna()
#参数
how='all'#删除全为空值的行或列
inplace=True#覆盖数据
axis#选择行或列
异常值处理
异常值指不合理的值,一般直接删除。
处理即筛选和覆盖。
数据保存
df.to_csv("文件名.csv")
df.to_excel("文件名.xlsx")
二、数据分析
1. 数据格式转换
查看格式
df=pd.read_excel("豆瓣电影数据.xlsx")
print(df['投票人数'].dtype)
#float64
格式转换
df['投票人数']=df['投票人数'].astype('int')
print(df['投票人数'].dtype)
#int32
部分数据看起来没有问题实则格式可能存在异常,可以通过格式转换查找异常值,异常值无法转换会报错,重新赋值即可。
2. 排序
默认排序为index。
根据某列值排序
#默认升序
print(df.sort_values(by='投票人数')[:5])
'''
Unnamed: 0 名字 投票人数 ... 年代 评分 首映地点
19797 19797 女教徒 -118.0 ... 1966 7.8 美国
19777 19777 皇家大贼 皇家大 -80.0 ... 1985 6.3 美国
19786 19786 日本的垃圾去中国大陆 にっぽんの“ゴミ” 大陆へ渡る ~中国式リサイクル錬 -80.0 ... 2004 7.9 美国
[3 rows x 10 columns]
'''
#降序排列
print(df.sort_values(by='投票人数',ascending=False)[:3])
'''
Unnamed: 0 名字 投票人数 类型 ... 时长 年代 评分 首映地点
0 0 肖申克的救赎 692795.0 剧情/犯罪 ... 142 1994 9.6 多伦多电影节
9 9 这个杀手不太冷 662552.0 剧情/动作/犯罪 ... 133 1994 9.4 法国
22 22 盗梦空间 642134.0 剧情/动作/科幻/悬疑/冒险 ... 148 2010 9.2 中国大陆
[3 rows x 10 columns]
'''
根据多个列值排序
print(df.sort_values(by=['评分','投票人数'])[:3])
'''
Unnamed: 0 名字 投票人数 类型 ... 时长 年代 评分 首映地点
29100 29100 都是手机惹的祸 42.0 喜剧 ... 60 2012 2.0 中国大陆
36080 36080 NaN 1334.0 喜剧/爱情 ... 91 2014 2.1 中国大陆
13137 13137 嫁给大山的女人 2690.0 剧情 ... 88 2009 2.1 中国大陆
[3 rows x 10 columns]
'''
评分相同则按照投票人数排序。
多列值by后跟一个列表。
3. 统计分析
(1)描述性统计
描述数值型数据。经常可以发现异常值。
print(df.describe())
'''
Unnamed: 0 投票人数 评分
count 38738.000000 38738.000000 38738.000000 #个数
mean 19368.500000 6185.833702 6.935704
std 11182.841701 26143.518786 1.270101
min 0.000000 -118.000000 2.000000
25% 9684.250000 98.000000 6.300000
50% 19368.500000 341.000000 7.100000
75% 29052.750000 1739.750000 7.800000
max 38737.000000 692795.000000 9.900000
'''
(2)特殊值
print(df['投票人数'].max())
#692795.0
均值 mean
中位数 median
方差 var
标准差 std
加和 sum
(3)相关系数和协方差
#相关系数
print(df[['投票人数','评分']].corr())
'''
投票人数 评分
投票人数 1.000000 0.122883
评分 0.122883 1.000000
'''
协方差 cov
(4)删除异常值
df.drop(df[df.['年代']>2030.index,inplace=True)
删除后index不再是连续值,可以重新赋值。
df.index=range(len(df))
(5)计数
len(df) #有多少行
#唯一值
df['产地'].unique()
#唯一值计数
len(df['产地'].unique())
去除重复值,如“美国”和“USA”
#将“USA”替换为“美国”,列表进行多个替换
df['产地'].repalce(['USA','苏联'],['美国','俄罗斯'],inplace=True)
某个值对应多少个数据
#每个年代对应多少个电影,数量降序排列
df['年代'].value_counts()
三、数据透视 pivot_table
1. 基础形式+多索引+指定统计数据
#根据年代分类汇总,数值型变量计算均值
print(pd.pivot_table(df,index=['年代','产地'],values=['评分']))
2. 指定统计函数
(1)计算总和和均值
pd.pivot_table(df,index=['年代'],values=['评分','投票人数'],aggfunc=[np.sum,np.mean])
(2)不同值执行不同函数
pd.pivot_table(df,index=['年代'],values=['评分','投票人数'],aggfunc={'投票人数':np.sum,'评分':np.mean})
3. 填充
移除非数值并将其设置为0
pd.pivot_table(df,index=['年代'],values=['评分','投票人数'],aggfunc=[np.sum,np.mean],fill_value=0)
4. 在下方显示总和数据
pd.pivot_table(df,index=['年代'],values=['评分','投票人数'],aggfunc=[np.sum,np.mean],fill_value=0,margins=True)
5. 设置展示的信息数量
pd.set_option('max_column',100)
pd.set_option('max_rows',500)
6. 透视表过滤
table=pd.pivot_table(df,index=['年代'],values=['评分','投票人数'],aggfunc=[np.sum,np.mean],fill_value=0,margins=True)
table为DataFrame数据
四、