【甘道夫】Pandas 基础知识总结

1.简介

pandas包括3类核心数据结构:

一维:pandas.core.series.Series

二维:pandas.core.frame.DataFrame

三维:pandas.core.panel.Panel(从0.20.0版本开始不建议使用该结构,未来将移除该结构!)

其中最核心的是Series和DataFrame。

series 和 dataframe的区别与联系:

区别:series,只是一个一维数据结构,它由index和value组成。dataframe,是一个二维结构,除了拥有index和value之外,还拥有column。

联系:dataframe由多个series组成,无论是行还是列,单独拆分出来都是一个series。

2.Dataframe常用操作代码演示

------------------------------------Part1:创建 ------------------------------------

>>> import pandas as pd

# 通过读入'\t'分割的csv文件创建dataframe,指定数据中没有表头,通过names指定表头

# 指定第0列是行索引(也可不指定,行索引就是递增数字),指定编码为utf-8

>>> dfc = pd.read_csv('/xxx/test.csv', sep='\t', header=None, names = ['man','woman'], index_col =0, encoding='utf-8')

# 以下演示基于数据集创建dataframe

>>> data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],

                    'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],

                    'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],

                    'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}

>>> labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

>>> df = pd.DataFrame(data, index=labels)

>>> df

animal age visits priority

a cat 2.5 1 yes

b cat 3.0 3 yes

c snake 0.5 2 no

d dog NaN 3 yes

e dog 5.0 2 no

f cat 2.0 3 no

g snake 4.5 1 no

h cat NaN 1 yes

i dog 7.0 2 no

j dog 3.0 1 no

------------------------------------ Part2:索引 ------------------------------------

# 基础行索引:当索引对象是行号切片时就是行索引,不支持指定单个数字

>>> df[1:3] # 可以用负数表示倒数第几行,例如df[-3:]表示最后3行

animal age visits priority

b cat 3.0 3 yes

c snake 0.5 2 no

>>> df['c':'f'] # 通过行标签的切片形式取出部分行

animal age visits priority

c snake 0.5 2 no

d dog NaN 3 yes

e dog 5.0 2 no

f cat 2.0 3 no

# 基础列索引:当索引对象是列名时就是列索引

>>> df["age"]

a 2.5

b 3.0

c 0.5

d NaN

e 5.0

f 2.0

g 4.5

h NaN

i 7.0

j 3.0

Name: age, dtype: float64

# 基础列索引:索引对象也可以是列名的list

>>> df[['age', 'animal']]

age animal

a 2.5 cat

b 3.0 cat

c 0.5 snake

d NaN dog

e 5.0 dog

f 2.0 cat

g 4.5 snake

h NaN cat

i 7.0 dog

j 3.0 dog

# 位置索引:通过 iloc 指定行、列的序号切片

>>> df.iloc[2:4,1:4] # 同时通过序号切片索引行列,也可只索引行

age visits priority

c 0.5 2 no

d NaN 3 yes

>>> df.iloc[[1,3],[2,3]] # 通过列表格式分别指定需要取回的行和列

visits priority

b 3 yes

d 3 yes

# 标签索引:通过 loc 指定行、列的标签列表

>>> df.loc['a', 'animal'] # 指定行、列标签取出指定位置的元素

'cat'

>>> df.loc[['a','c'], ['animal', 'visits']] # 通过行、列标签列表指定需要取出的行和列

animal visits

a cat 1

c snake 2

>>> df.loc['a':'c', ['animal', 'visits']] # 通过行标签切片格式指定行范围

animal visits

a cat 1

b cat 3

c snake 2

# 注意,混合索引 ix 最新版本已不再支持

------------------------------------ Part3:观察操作 ------------------------------------

# 查看dataframe形状

>>> df.shape

(10, 4)

# 查看dataframe基础信息

>>> df.info()

<class 'pandas.core.frame.DataFrame'>

Index: 10 entries, a to j

Data columns (total 4 columns):

animal 10 non-null object

age 8 non-null float64

visits 10 non-null int64

priority 10 non-null object

dtypes: float64(1), int64(1), object(2)

memory usage: 720.0+ bytes

# 查看dataframe统计数据,可为数值归一化做参考

>>> des = df.describe()   

>>> des # count 总数,mean 均值,std 标准差

age visits

count 8.000000 10.000000

mean 3.437500 1.900000

std 2.007797 0.875595

min 0.500000 1.000000

25% 2.375000 1.000000

50% 3.000000 2.000000

75% 4.625000 2.750000

max 7.000000 3.000000

>>> df.head(10) # 查看前10行

>>> df.tail(20) # 查看后20行

>>> df.index # 查看行索引

>>> df.columns # 查看列名

>>> df.values # 查看数据

>>> df.T # 行列转置

>>> df.sort_values(by='visits', ascending=True) # 根据visits列的值升序排序

>>> df.sort_index(axis=1, ascending=False) # 按列label名称降序排序

>>> df.max() # 查看各列最大值

>>> df["age"].max() # 查看age列最大值

>>> df["age"].idxmax() # 查看age列最大值的行index,注意,同功能的argmax在最新版本已不推荐使用

>>> df['age'].count() # 统计age列非NA行数

>>> df[df['age']>=3] # 查询age大于等于3的行

>>> df[(df['age']>=3)&(df['visits']==2)] # 查询age大于等于3,同时visits等于2的行

>>> df[df['age'].isin(['2.5','3.0'])] # age列的值在列表['2.5','3.0']内

------------------------------------ Part4:其它操作 ------------------------------------

dataframe.dropna() # 去除所有包含np.nan的行

dataframe.fillna(value=16) # 将所有的np.nan用16填充

pd.isna(dataframe) # 将整个df内所有值转换为True/False,表示每个元素是否是np.nan

dataframe_cp = dataframe.copy() # 复制df

# 拼接concat

label = dataframe.pop('label') # 从df里取出label列创建一个Series,df里会减少该列

pd.concat([df,label],axis=1) #将取出的列和现在的df拼接为之前的df,该df和之前有相同的列,知识列顺序不同

# 将归一化后的age和visits列拼接到原df右侧。注意,axis=0代表行拼接,axis=1代表列拼接

pd.concat([df,df["age"]/df["age"].max(),df["visits"]/df["visits"].max()],axis=1)   

# 拼接前3行和8行以后数据

pd.concat([df[:3],df[8:]],axis=0)

# 将dataframe转换成numpy

dataframe.to_numpy()

# 为df增加新的列

s1 = pd.Series(6,index=df.index)

df['s1'] = s1

# 修改指定元素的值

df.at['a','s1'] = 666 # 通过行列label指定位置修改,将‘a’行,‘s1’列的元素值修改为666

df.iat[1,4] = 888 # 通过行列序号指定位置修改,将第1行,第4列的元素值修改为888

df.loc[:,['s1']] = 'helloworld' # 通过loc,将s1列所有值修改为‘helloworld’

df.iloc[:,[4]] = 'hello' # 通过iloc,将第4列所有值修改为‘hello’

df.loc[(df['animal']=='dog')&(df['age']>=5.0),['age']] = 16 # 将age>=5的dog的age全改为16

# 归一化

df_norm = (df - df.min()) / (df.max() - df.min())

# 字符串操作

df['animal'].str.upper() # 将animal列的str类型全变为大写,相反的,lower()是变为小写

3.重要资料

官网文档:http://pandas.pydata.org/pandas-docs/stable/getting_started/10min.html

loc方法api文档:http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html#pandas.DataFrame.loc

pandas速查表中文版(非最新版本,仅供参考):

【基础版】

【进阶版】

猜你喜欢

转载自blog.csdn.net/u010967382/article/details/89490502
今日推荐