CH01 - Pandas基础

import numpy as np
import pandas as pd
pd.__version__
'1.0.3'

一、文件读取与写入

1.1、读取文件

1.1.1 csv格式

df = pd.read_csv('C:/Users/admin/Desktop/joyful-pandas-master/joyful-pandas-master/data/table.csv')
df.head()
SchoolClassIDGenderAddressHeightWeightMathPhysics
0S_1C_11101Mstreet_11736334.0A+
1S_1C_11102Fstreet_21927332.5B+
2S_1C_11103Mstreet_21868287.2B+
3S_1C_11104Fstreet_21678180.4B-
4S_1C_11105Fstreet_41596484.8B+

1.1.2 txt格式

df_txt = pd.read_table('C:/Users/admin/Desktop/joyful-pandas-master/joyful-pandas-master/data/table.txt')
df_txt
col1col2col3col4
02a1.4apple
13b3.4banana
26c2.5orange
35d3.2lemon

1.1.3 xls或xlsx格式

需要安装xlrd包

df_excel = pd.read_excel('C:/Users/admin/Desktop/joyful-pandas-master/joyful-pandas-master/data/table.xlsx')
df_excel.head()
SchoolClassIDGenderAddressHeightWeightMathPhysics
0S_1C_11101Mstreet_11736334.0A+
1S_1C_11102Fstreet_21927332.5B+
2S_1C_11103Mstreet_21868287.2B+
3S_1C_11104Fstreet_21678180.4B-
4S_1C_11105Fstreet_41596484.8B+

1.2、写入文件

1.2.1 csv格式写入

注意:参数index=False时,保存时除去行索引

df.to_csv('C:/Users/admin/Desktop/joyful-pandas-master/joyful-pandas-master/data/new_table1.csv')

1.2.2 xls或xlsx格式写入

注意:需要安装openpyxl包

df.to_excel('C:/Users/admin/Desktop/joyful-pandas-master/joyful-pandas-master/data/new_table11.xlsx',sheet_name = "Sheet1",index = False)

二、基本数据结构

2.1、Series介绍

2.1.1 Series创建

注意:1、series,只是一个一维数据结构,它由index和value组成。2、series其最常用的属性为值(values),索引(index),名字(name),类型(dtype);3、series, 就是一个 一维 的数据结构,它是由index和 value 组成。

s = pd.Series(np.random.randn(5),index = ['a','b','c','d','e'],name = '这是一个Series',dtype = 'float64')
s
a    0.301189
b    1.542214
c    0.249707
d   -0.130043
e   -1.195499
Name: 这是一个Series, dtype: float64

2.1.2 Series属性

s.values
array([ 0.30118877,  1.54221417,  0.24970685, -0.1300435 , -1.19549855])
s.name
'这是一个Series'
s.index
Index(['a', 'b', 'c', 'd', 'e'], dtype='object')

2.1.3 Series取值

s['a']
0.3011887697818808

2.1.4 Series方法调用

s.mean()
0.15351354975253528
print([attr for attr in dir(s) if not attr.startswith('_')])
['T', 'a', 'abs', 'add', 'add_prefix', 'add_suffix', 'agg', 'aggregate', 'align', 'all', 'any', 'append', 'apply', 'argmax', 'argmin', 'argsort', 'array', 'asfreq', 'asof', 'astype', 'at', 'at_time', 'attrs', 'autocorr', 'axes', 'b', 'between', 'between_time', 'bfill', 'bool', 'c', 'clip', 'combine', 'combine_first', 'convert_dtypes', 'copy', 'corr', 'count', 'cov', 'cummax', 'cummin', 'cumprod', 'cumsum', 'd', 'describe', 'diff', 'div', 'divide', 'divmod', 'dot', 'drop', 'drop_duplicates', 'droplevel', 'dropna', 'dtype', 'dtypes', 'duplicated', 'e', 'empty', 'eq', 'equals', 'ewm', 'expanding', 'explode', 'factorize', 'ffill', 'fillna', 'filter', 'first', 'first_valid_index', 'floordiv', 'ge', 'get', 'groupby', 'gt', 'hasnans', 'head', 'hist', 'iat', 'idxmax', 'idxmin', 'iloc', 'index', 'infer_objects', 'interpolate', 'is_monotonic', 'is_monotonic_decreasing', 'is_monotonic_increasing', 'is_unique', 'isin', 'isna', 'isnull', 'item', 'items', 'iteritems', 'keys', 'kurt', 'kurtosis', 'last', 'last_valid_index', 'le', 'loc', 'lt', 'mad', 'map', 'mask', 'max', 'mean', 'median', 'memory_usage', 'min', 'mod', 'mode', 'mul', 'multiply', 'name', 'nbytes', 'ndim', 'ne', 'nlargest', 'notna', 'notnull', 'nsmallest', 'nunique', 'pct_change', 'pipe', 'plot', 'pop', 'pow', 'prod', 'product', 'quantile', 'radd', 'rank', 'ravel', 'rdiv', 'rdivmod', 'reindex', 'reindex_like', 'rename', 'rename_axis', 'reorder_levels', 'repeat', 'replace', 'resample', 'reset_index', 'rfloordiv', 'rmod', 'rmul', 'rolling', 'round', 'rpow', 'rsub', 'rtruediv', 'sample', 'searchsorted', 'sem', 'set_axis', 'shape', 'shift', 'size', 'skew', 'slice_shift', 'sort_index', 'sort_values', 'squeeze', 'std', 'sub', 'subtract', 'sum', 'swapaxes', 'swaplevel', 'tail', 'take', 'to_clipboard', 'to_csv', 'to_dict', 'to_excel', 'to_frame', 'to_hdf', 'to_json', 'to_latex', 'to_list', 'to_markdown', 'to_numpy', 'to_period', 'to_pickle', 'to_sql', 'to_string', 'to_timestamp', 'to_xarray', 'transform', 'transpose', 'truediv', 'truncate', 'tshift', 'tz_convert', 'tz_localize', 'unique', 'unstack', 'update', 'value_counts', 'values', 'var', 'view', 'where', 'xs']

2.2、DataFrame介绍

2.2.1 DataFrame创建

注意:dataframe是一个二维结构,除了拥有index和value之外,还拥有column。dataframe由多个series组成,无论是行还是列,单独拆分出来都是一个series。

df = pd.DataFrame({'col1':list('abcde'),'col2':range(5,10),'col3':[1.3,2.5,3.6,4.6,5.8]},index = list('一二三四五'))
df
col1col2col3
a51.3
b62.5
c73.6
d84.6
e95.8

2.2.2 DataFrame取值

df['col1']
一    a
二    b
三    c
四    d
五    e
Name: col1, dtype: object
type(df)
pandas.core.frame.DataFrame
type(df['col1'])
pandas.core.series.Series

2.2.3 DataFrame修改行名或列名

注意:不改变原数据

df.rename(index = {'一':'1'}, columns = {'col1':'new_col1'})
new_col1col2col3
1a51.3
b62.5
c73.6
d84.6
e95.8

2.2.4 DataFrame调用属性和方法

df.index
Index(['一', '二', '三', '四', '五'], dtype='object')
df.values
array([['a', 5, 1.3],
       ['b', 6, 2.5],
       ['c', 7, 3.6],
       ['d', 8, 4.6],
       ['e', 9, 5.8]], dtype=object)
df.columns
Index(['col1', 'col2', 'col3'], dtype='object')
type(df.columns)
pandas.core.indexes.base.Index
df.shape
(5, 3)

注意:df.mean()中参数axis

df.mean()
col2    7.00
col3    3.56
dtype: float64

2.2.5 索引对齐特性

df1 = pd.DataFrame({'A':[1,2,3]},index = [1,2,3])
df2 = pd.DataFrame({'A':[1,2,3]},index = [3,1,2])
df1
A
11
22
33
df2
A
31
12
23
df1-df2
A
1-1
2-1
32

2.2.6 列的删除与添加

注意:对于删除而言,可以使用drop函数或del或pop;drop方法默认原数据不改变,设置inplace=True后会直接在原DataFrame中改动。

df.drop(index = '五',columns = 'col1')
col2col3
51.3
62.5
73.6
84.6
df['col1'] = [1,2,3,4,5]
del df['col1']
df
col2col3
51.3
62.5
73.6
84.6
95.8

pop方法直接在原来的DataFrame上操作,且返回被删除的列,与python中的pop函数类似

df['col1'] = [1,2,3,4,5]
df.pop('col1')
一    1
二    2
三    3
四    4
五    5
Name: col1, dtype: int64
df
col2col3
51.3
62.5
73.6
84.6
95.8
df1['B'] = list('abc')
df1
AB
11a
22b
33c

新增列:1、可以直接增加新的列,也可以使用assign方法;2、但assign方法不会对原DataFrame做修改。

df1.assign(c = pd.Series(list('def')))
ABc
11ae
22bf
33cNaN
df1
AB
11a
22b
33c

2.2.7 根据数据类型进行选择

df.select_dtypes(include = ['number']).head()
col2col3
51.3
62.5
73.6
84.6
95.8
df.select_dtypes(include=['float']).head()
col3
1.3
2.5
3.6
4.6
5.8

2.2.8 将Series转换为DataFrame

s = df.mean()
s.name = 'to_DataFrame'
s
col2    7.00
col3    3.56
Name: to_DataFrame, dtype: float64
type(s)
pandas.core.series.Series
s.to_frame()
to_DataFrame
col27.00
col33.56
s.to_frame().T
col2col3
to_DataFrame7.03.56

三、常用数据结构

3.1 head与tail

注意:参数设置

df = pd.read_csv('C:/Users/admin/Desktop/joyful-pandas-master/joyful-pandas-master/data/table.csv')
df.head()
SchoolClassIDGenderAddressHeightWeightMathPhysics
0S_1C_11101Mstreet_11736334.0A+
1S_1C_11102Fstreet_21927332.5B+
2S_1C_11103Mstreet_21868287.2B+
3S_1C_11104Fstreet_21678180.4B-
4S_1C_11105Fstreet_41596484.8B+
df.tail()
SchoolClassIDGenderAddressHeightWeightMathPhysics
30S_2C_42401Fstreet_21926245.3A
31S_2C_42402Mstreet_71668248.7B
32S_2C_42403Fstreet_61586059.7B+
33S_2C_42404Fstreet_21608467.7B
34S_2C_42405Fstreet_61935447.6B
df.head(3)
SchoolClassIDGenderAddressHeightWeightMathPhysics
0S_1C_11101Mstreet_11736334.0A+
1S_1C_11102Fstreet_21927332.5B+
2S_1C_11103Mstreet_21868287.2B+

3.2 unique和nunique

注意:1、nunique显示有多少个唯一值;2、unique显示所有的唯一值

df['Physics'].nunique()
7
df['Physics'].unique()
array(['A+', 'B+', 'B-', 'A-', 'B', 'A', 'C'], dtype=object)

3.3 count和value_count

注意:1、count返回非缺失值元素个数;2、value_counts返回每个元素有多少个

df['Physics'].count()
35
df['Physics'].value_counts()
B+    9
B     8
B-    6
A     4
A-    3
A+    3
C     2
Name: Physics, dtype: int64

3.4 describe和info

注意:1、info函数返回有哪些列、有多少非缺失值、每列的类型;2、describe默认统计数值型数据的各个统计量

df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 35 entries, 0 to 34
Data columns (total 9 columns):
 #   Column   Non-Null Count  Dtype  
---  ------   --------------  -----  
 0   School   35 non-null     object 
 1   Class    35 non-null     object 
 2   ID       35 non-null     int64  
 3   Gender   35 non-null     object 
 4   Address  35 non-null     object 
 5   Height   35 non-null     int64  
 6   Weight   35 non-null     int64  
 7   Math     35 non-null     float64
 8   Physics  35 non-null     object 
dtypes: float64(1), int64(3), object(5)
memory usage: 2.6+ KB
df.describe()
IDHeightWeightMath
count35.0000035.00000035.00000035.000000
mean1803.00000174.14285774.65714361.351429
std536.8774113.54109812.89537719.915164
min1101.00000155.00000053.00000031.500000
25%1204.50000161.00000063.00000047.400000
50%2103.00000173.00000074.00000061.700000
75%2301.50000187.50000082.00000077.100000
max2405.00000195.000000100.00000097.000000
df['Physics'].describe()
count     35
unique     7
top       B+
freq       9
Name: Physics, dtype: object

3.5 idxmax和nlargest

注意:1、idxmax函数返回最大值,在某些情况下特别适用,idxmin功能类似;2、nlargest函数返回前几个大的元素值,nsmallest功能类似

df['Math'].idxmax()
5
df['Math'].nlargest(4)
5     97.0
28    95.5
11    87.7
2     87.2
Name: Math, dtype: float64

3.6 clip和replace

注意:1、clip和replace是两类替换函数,clip是对超过或者低于某些值的数进行截断;2、replace是对某些值进行替换;3、通过字典,可以直接在表中修改

df['Math'].head()
0    34.0
1    32.5
2    87.2
3    80.4
4    84.8
Name: Math, dtype: float64
df['Math'].clip(33,80).head()
0    34.0
1    33.0
2    80.0
3    80.0
4    80.0
Name: Math, dtype: float64
df['Math'].mad()
16.924244897959188
df['Address'].head()
0    street_1
1    street_2
2    street_2
3    street_2
4    street_4
Name: Address, dtype: object
df['Address'].replace(['street_1','street_2'],['one','two']).head()
0         one
1         two
2         two
3         two
4    street_4
Name: Address, dtype: object
df.replace({'Address':{'street_1':'one','street_2':'two'}}).head()
SchoolClassIDGenderAddressHeightWeightMathPhysics
0S_1C_11101Mone1736334.0A+
1S_1C_11102Ftwo1927332.5B+
2S_1C_11103Mtwo1868287.2B+
3S_1C_11104Ftwo1678180.4B-
4S_1C_11105Fstreet_41596484.8B+

3.7 APPLy函数

注意:1、对于Series,它可以迭代每一列的值操作;2、对于DataFrame,它可以迭代每一个列操作.

df['Math'].apply(lambda x : str(x)+'!').head()
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()
SchoolClassIDGenderAddressHeightWeightMathPhysics
0S_1!C_1!1101!M!street_1!173!63!34.0!A+!
1S_1!C_1!1102!F!street_2!192!73!32.5!B+!
2S_1!C_1!1103!M!street_2!186!82!87.2!B+!
3S_1!C_1!1104!F!street_2!167!81!80.4!B-!
4S_1!C_1!1105!F!street_4!159!64!84.8!B+!

四、排序

df.set_index('Math').head()
SchoolClassIDGenderAddressHeightWeightPhysics
Math
34.0S_1C_11101Mstreet_117363A+
32.5S_1C_11102Fstreet_219273B+
87.2S_1C_11103Mstreet_218682B+
80.4S_1C_11104Fstreet_216781B-
84.8S_1C_11105Fstreet_415964B+
df.set_index('Math').sort_index().head()
SchoolClassIDGenderAddressHeightWeightPhysics
Math
31.5S_1C_31301Mstreet_416168B+
32.5S_1C_11102Fstreet_219273B+
32.7S_2C_32302Mstreet_517188A
33.8S_1C_21204Fstreet_516263B
34.0S_1C_11101Mstreet_117363A+
df.sort_values(by = 'Class').head()
SchoolClassIDGenderAddressHeightWeightMathPhysics
0S_1C_11101Mstreet_11736334.0A+
19S_2C_12105Mstreet_41708134.2A
18S_2C_12104Fstreet_51599772.2B+
16S_2C_12102Fstreet_61616150.6B+
15S_2C_12101Mstreet_71748483.3C
df.sort_values(by=['Address','Height']).head()
SchoolClassIDGenderAddressHeightWeightMathPhysics
0S_1C_11101Mstreet_11736334.0A+
11S_1C_31302Fstreet_11755787.7A-
23S_2C_22204Mstreet_11757447.2B-
33S_2C_42404Fstreet_21608467.7B
3S_1C_11104Fstreet_21678180.4B-

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值