在Pandas中根据多列的值分割数据框架
在这篇文章中,我们将看到如何使用Python通过各种方法和基于各种参数来划分一个数据框架。为了根据列中的值将一个数据框分成两个或多个独立的数据框,我们首先创建一个数据框。
创建一个用于去污的数据框架:
# importing pandas as pd
import pandas as pd
# dictionary of lists
dict = {'First_Name': ["Aparna", "Pankaj", "Sudhir",
"Geeku", "Anuj", "Aman",
"Madhav", "Raj", "Shruti"],
'Last_Name': ["Pandey", "Gupta", "Mishra",
"Chopra", "Mishra", "Verma",
"Sen", "Roy", "Agarwal"],
'Email_ID': ["apandey@gmail.com", "pankaj@gmail.com",
"sumishra23@gmail.com", "cgeeku@yahoo.com",
"anuj24@gmail.com", "amanver@yahoo.com",
"madhav1998@gmail.com", "rroy7@gmail.com",
"sagarwal36@gmail.com"],
'Degree': ["MBA", "BCA", "M.Tech", "MBA", "B.Sc",
"B.Tech", "B.Tech", "MBA", "M.Tech"],
'Score': [90, 40, 75, 98, 94, 90, 80, 90, 95]}
# creating dataframe
df = pd.DataFrame(dict)
print(df)
输出:
方法1:通过布尔索引法
我们可以通过使用布尔索引方法和提及所需的标准,从一个给定的数据框架中根据某个列的值创建多个数据框架。
例子1:为分数大于等于80分的学生创建一个数据框架
# creating a new dataframe by applying the required
# conditions in []
df1 = df[df['Score'] >= 80]
print(df1)
输出:
示例2:为Last_Name为Mishra的学生创建一个数据框架。
# Creating on the basis of Last_Name
dfname = df[df['Last_Name'] == 'Mishra']
print(dfname)
输出:
我们也可以通过设置适当的条件对其他列进行同样的处理
方法2:用掩码变量进行布尔索引
我们为前面的方法中的列的条件创建一个掩码变量
例子1:要获得学位为MBA的学生的数据框架
# creating the mask variable with appropriate
# condition
mask_var = df['Degree'] =='MBA'
# creating a dataframe
df1_mask = df[mask_var]
print(df1_mask)
输出 :
例子2:要为其余的学生获得一个数据框架
为了获得数据框架中的其他数值,我们可以简单地在掩码变量后面加一个~(tilde)来反转它。
# creating dataframe with inverted mask variable
df2_mask = df[~mask_var]
print(df2_mask)
输出 :
方法3:使用 groupby()函数
使用groupby(),我们可以用一个特定的列值对行进行分组,然后作为一个单独的数据帧显示。
例子1:根据学位对所有学生进行分组并按要求显示
# Creating an object using groupby
grouped = df.groupby('Degree')
# the return type of the object 'grouped' is
# pandas.core.groupby.generic.DataFrameGroupBy.
# Creating a dataframe from the object using get_group().
# dataframe of students with Degree as MBA.
df_grouped = grouped.get_group('MBA')
print(df_grouped)
输出:学位为MBA的学生数据框架
例子2:根据学生的分数对所有学生进行分组,并按要求显示
# Creating another object using groupby
grouped2 = df.groupby('Score')
# the return type of the object 'grouped2' is
# pandas.core.groupby.generic.DataFrameGroupBy.
# Creating a dataframe from the object
# using get_group() dataframe of students
# with Score = 90
df_grouped2 = grouped2.get_group(90)
print(df_grouped2)
输出:得分=90的学生数据框架。