ps:本次pandas训练使用1.0.3版本,如低版本可通过 pip install --upgrade pandas==1.0.3 指定版本升级
#导入pandas
import pandas as pd
#导入numpy
import numpy as np
#查看pandas 版本
pd.__version__
#csv格式
df = pd.read_csv('data/table.csv')
#txt或者日常运维常见log、acc日志等
df_txt = pd.read_table('data/table.txt')
df_txt = pd.read_table('data/acc.log',sep='\s+') #sep 设置对应的分隔符
#xls或xlsx文件
df_excel = pd.read_excel('data/table.xlsx')
#同时以上路径均为相对路径,可设置绝对路径服务,window环境如下绝对路径示例
df_win = pd.read_excel('c:\\users\\downloads\\data\\table.xlsx')
#sql读取
#sqlite3 示例
import sqlite3
conn = sqlite3.connect('test.db') #相对路径,存放在jupyter打开路径
#创建表
conn.execute('create table person(id varchar(8) primary key,name varchar(8))')
conn.commit()
#导入数据
conn.execute('insert into person values('1','jerry'),('2','tom')')
conn.commit()
#读取sql内容
sql_ln = 'select id,name from person'
pd.read_sql(sql_ln,conn)
#csv格式
df.to_csv('data/new_index_table.csv')
df.to_csv('data/new_noindex_table.csv',index=False)#忽略索引
#xlsx格式
df.to_excel('dxata/new_table2.xlsx', sheet_name='Sheet1')
s =pd.Series(np.random.randn(5),index=['a','b','c','d','e'],name='一个Series数组',dtype='float64')
#s展示如下
a 0.486934
b 0.005319
c 0.041949
d -0.500936
e 0.404433
Name: 一个Series数组, dtype: float64
#最常用的属性为值(values),索引(index),名字(name),类型(dtype)
s.values
#输出
array([ 1.06995138, -0.10068972, 0.00838377, -1.13360582, -0.88613285])
#dtype数据类型如下
1. float
2. int
3. bool
4. datetime64[ns]
5. datetime64[ns, tz]
6. timedelta[ns]
7. category
8. object
#Series转换为DataFrame
s.to_frame()
df = pd.DataFrame({'col1':list('abcde'),'col2':range(5,10),'col3':[1.3,2.5,3.6,4.6,5.8]},
index=list('一二三四五'))
#df输出如下
col1 col2 col3
一 a 5 1.3
二 b 6 2.5
三 c 7 3.6
四 d 8 4.6
五 e 9 5.8
#选择指定列
df['col2']
一 5
二 6
三 7
四 8
五 9
Name: col2, dtype: int64
df[['col1','col3']]
col1 col3
一 a 1.3
二 b 2.5
三 c 3.6
四 d 4.6
五 e 5.8
df.loc[:,['col1','col2']]
col1 col2
一 a 5
二 b 6
三 c 7
四 d 8
五 e 9
#单独选择一列为Series
type(df['col1'])
pandas.core.series.Series
#cloumns 及index 重命名
df.rename(index={'一':'one','二':'two'},columns={'col1':'new_col1'})
new_col1 col2 col3
one a 5 1.3
two b 6 2.5
三 c 7 3.6
四 d 8 4.6
五 e 9 5.8
#索引对齐特性
#如下相减是安装索引1、2、3顺序来进行的
df1 = pd.DataFrame({'A':[1,2,3]},index=[1,2,3])
df2 = pd.DataFrame({'A':[1,2,3]},index=[3,1,2])
df1-df2
A
1 -1
2 -1
3 2
#列删除及添加
df['col4'] = [1,2,3,4,5]
col1 col2 col3 col4
一 a 5 1.3 1
二 b 6 2.5 2
三 c 7 3.6 3
四 d 8 4.6 4
五 e 9 5.8 5
df.pop('col4')
一 1
二 2
三 3
四 4
五 5
Name: col4, dtype: int64
del df['col1']
df
col2 col3
一 5 1.3
二 6 2.5
三 7 3.6
四 8 4.6
五 9 5.8
#assign也是按照索引对齐,所以索引3为NaN 缺少值,不会对原DataFrame修改
pd.Series(list('def')
0 d
1 e
2 f
dtype: object
df1.assign(C=pd.Series(list('def')))
A C
1 1 e
2 2 f
3 3 NaN
#nunique显示有多少个唯一值
df['Physics'].nunique()
``#unique显示所有的唯一值
df['Physics'].unique()
array(['A+', 'B+', 'B-', 'A-', 'B', 'A', 'C'], dtype=object)
`
unique显示所有的唯一值
df['Physics'].unique()
## 标题
#idxmax函数返回最大值的行数,idxmin功能相反
df['Math'].idxmax()
5
df['Math'].idxmin()
10
df['Math'].apply(lambda x:str(x)+'!').head() #可以使用lambda表达式,也可以使用函数
0 34.0!
1 32.5!
2 87.2!
3 80.4!
4 84.8!
Name: Math, dtype: object
df.apply(lambda x:x.apply(lambda x:str(x)+'!')).head() #这是一个稍显复杂的例子,有利于理解apply的功能
School Class ID Gender Address Height Weight Math Physics
0 S_1! C_1! 1101! M! street_1! 173! 63! 34.0! A+!
1 S_1! C_1! 1102! F! street_2! 192! 73! 32.5! B+!
2 S_1! C_1! 1103! M! street_2! 186! 82! 87.2! B+!
3 S_1! C_1! 1104! F! street_2! 167! 81! 80.4! B-!
4 S_1! C_1! 1105! F! street_4! 159! 64! 84.8! B+!