pandas 用来进行数据处理,其是基于numpy建立的库,因此每次import pandas的时候也需要import numpy
目录
pandas的两种数据结构
pandas有两种数据结构,即series和dataframe,其区别在于series用来存储一维数据,dataframe用来存储二维数据。
series
用来存储一维数组,其中label用来表示每个数据的含义
import pandas as pd
import numpy as np
# Creating empty series
ser = pd.Series()
print(ser)
# simple array
data = np.array(['g', 'e', 'e', 'k', 's'])
ser = pd.Series(data)
print(ser)
dataframe
二维数据,需要两个label用来表示数据
import pandas as pd
# Calling DataFrame constructor
df = pd.DataFrame()
print(df)
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is',
'portal', 'for', 'Geeks']
# Calling DataFrame constructor on list
df = pd.DataFrame(lst)
print(df)
dataframe常用方法
columns
columns用来返回列lable
import pandas as pd
# Creating the DataFrame
df = pd.DataFrame({'Weight':[45, 88, 56, 15, 71],
'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],
'Age':[14, 25, 55, 8, 21]})
# Create the index
index_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']
# Set the index
df.index = index_
# Print the DataFrame
print(df)
result = df.columns
# Print the result
print(result)
也可对columns进行赋值
df.columns = ['Weight', 'Age', 'Name']
groupby
- 功能:通过一些关键字,将数据集分类,比如通过性别可以将数据集分为男女,以便后续的修改
- 用法:
- 只有一个label
-
# importing pandas module import pandas as pd # Define a dictionary containing employee data data1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df) df.groupby('Name') print(df.groupby('Name').groups) # Let's print the first entries # in all the groups formed. # 输出group之后每一个group的第一项 gk.first()
-
- 多个label
- 只有当所有选中的label项都相同的时候才能确定这几项属于同一组
-
import pandas as pd # Define a dictionary containing employee data data1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df) df.groupby(['Name', 'Qualification']) print(df.groupby(['Name', 'Qualification']).groups)
- 在groupby函数后面继续用函数
- .groups:将数据组织成keyword+位置的形式
- .sum:将数据组织成keyword+对应的group的总数
- sort = False,用来选择是否进行排序
-
df.groupby(['Name', 'Qualification']).groups df.groupby(['Name']).sum() df.groupby(['Name'], sort = False).sum()
- 只有一个label
- 数据处理过程
- 分类:grouping
- 处理
- 合并
- 相关链接
count计数
- 功能:返回数据集中数据的数量
- 用法:
-
df = pd.DataFrame({"Person": ["John", "Myla", "Lewis", "John", "Myla"], "Age": [24., np.nan, 21., 33, 26], "Single": [False, True, True, True, False]}) “”“ df Person Age Single 0 John 24.0 False 1 Myla NaN True 2 Lewis 21.0 True 3 John 33.0 True 4 Myla 26.0 False ”“” df.count() “”“ Person 5 Age 4 Single 5 dtype: int64 ”“”
-
drop删除
- 功能:从dataframe中删除一些数据
- 删除满足条件的行或者列
-
# 删除满足条件的行 df = df.drop(df[df['Weight'] < 160].index) print(df) # 删除满足条件的列 for column in df.columns: if 'eight' in column: df.drop(columns=column, inplace=True) print(df.head()) # 删除满足多个条件的行 df = df.drop(df[(df['Weight'] < 160) | (df['Height'] < 180)].index) print(df.head()) # 通过列下标删除列 df = df.drop(df.iloc[:, 1:3], axis = 1) print(df) #删除多行数据 df.drop(df.index[3:7],0,inplace=True)
- 相关链接
- 相关链接1
-
- 用法:
-
import numpy as np import pandas as pd df = pd.DataFrame(np.arange(12).reshape(3, 4), columns=['P', 'Q', 'R', 'S']) print(df) """ P Q R S 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 """ df.drop(['Q', 'R'], axis=1) #这里的axis表示删除的是行还是列,0表示行,1表示列 print(df) """ P S 0 0 3 1 4 7 2 8 11 """
-
- 相关链接
head前几条信息
- 功能:表示数据中的前几行信息
- 用法:
-
import pandas as pd import numpy as np data_set = pd.DataFrame({'Name': ['Rohit', 'Mohit', 'Shubh', 'Pranav', 'Shivam', 'Prince'], 'Class': ['10', '09', '11', '12', '05', '07']}) print(data_set.head(5)) ”“” Name Class 0 Rohit 10 1 Mohit 09 2 Shubh 11 3 Pranav 12 4 Shivam 05 “”“
-
- 相关链接
rename用来给dataframe换名
- 功能:用来给dataframe的行或者列换名称
- 用法:
-
import pandas as pd # making data frame from csv file data = pd.read_csv("nba.csv", index_col ="Name" ) # changing index cols with rename() data.rename(index = {"Avery Bradley": "NEW NAME", "Jae Crowder":"NEW NAME 2"}, inplace = True) # 这里将行名称Avery Bradley 改为NEW NAME,将Jae Crowder改为NEW NAME 2,其中inplace表示是否对原dataframe进行修改
- 参数:
- inplace表示是否对原来的dataframe进行修改
-
- 相关链接
pivot数据重新整理
- 功能:用来对原有的数据集进行整理
- 用法:
-
import pandas as pd # creating a dataframe df = pd.DataFrame({'A': ['John', 'Boby', 'Mina'], 'B': ['Masters', 'Graduate', 'Graduate'], 'C': [27, 23, 21]}) # values can be an object or a list df.pivot('A', 'B', 'C')
- 修改后
-
-
参数:
-
index:新构建的数据表的行名称
-
column:新构建的数据表的列名称
-
values:每个数据项的含义
-
- 相关链接
shape数据集大小
- 功能:表示数据集大小
- 用法:
-
import pandas as pd #initialize a dataframe df = pd.DataFrame() print('The DataFrame is :\n', df) #get dataframe shape shape = df.shape print('DataFrame Shape :', shape) print('Number of rows :', shape[0]) print('Number of columns :', shape[1])
-
- 相关链接