Pandas 是 Python 中最受欢迎的软件包之一,广泛用于数据操作。它是一个非常强大且用途广泛的软件包,使数据清理和整理变得更加轻松愉快。
Pandas 库对 Python 社区做出了巨大贡献,它使 Python 成为数据科学和分析领域的顶级编程语言之一。它已成为数据分析师和科学家进行数据分析和操作的首选。
什么是熊猫包?
Pandas 包具有许多功能,这些功能是数据处理和操作的本质。简而言之,它可以为您执行以下任务——
在本教程中,我们将使用两个数据集: 'income' 和 'iris' 。
-
'income' data : 该数据包含各米国各州从2002年到2015年的收入。该数据集包含51个观测值和16个变量。下载链接
-
'iris' 数据:它包含 150 个观测值和 5 个变量。我们有 3 种花(每种 50 朵花),所有花的萼片长度和宽度以及花瓣长度和宽度都已给出。下载链接
要记住的重要熊猫功能
以下是常见任务以及 pandas 函数的列表。
| 公用事业 | 功能 |
|---|---|
| 提取列名称 | df.列 |
| 选择前 2 行 | df.iloc[:2] |
| 选择前 2 列 | df.iloc[:,:2] |
| 按名称选择列 | df.loc[:,["col1","col2"]] |
| 选择随机编号 行数 | df.样本(n = 10) |
| 选择随机行的分数 | df.sample(frac = 0.2) |
| 重命名变量 | df.重命名() |
| 选择一列作为索引 | df.set_index() |
| 删除行或列 | df.drop() |
| 排序值 | df.sort_values() |
| 分组变量 | df.groupby( ) |
| 过滤 | df.查询() |
| 查找缺失值 | df.isnull( ) |
| 删除缺失值 | df.dropna( ) |
| 删除重复项 | df.drop_duplicates() |
| 创建假人 | pd.get_dummies( ) |
| 排行 | df.rank( ) |
| 累计金额 | df.cumsum( ) |
| 分位数 | df.分位数() |
| 选择数值变量 | df.select_dtypes() |
| 连接两个数据帧 | pd.concat() |
| 基于公共变量合并 | pd.合并() |
导入熊猫库
您需要先导入或加载 Pandas 库才能使用它。“Importing a library”就是把它加载到内存中,然后你就可以使用它了。运行以下代码导入 pandas 库:
import pandas as pd
“pd”是别名或缩写,将用作访问或调用 pandas 函数的快捷方式。要访问 pandas 库中的函数,您只需在每次需要应用时键入pd.function 而不是 pandas.function 。
导入数据集
要从 CSV 文件读取或导入数据,可以使用read_csv() 函数。 在该函数中,您需要指定 CSV 文件的文件位置。
income = pd.read_csv("C:\Users\Hp\Python\Basics\income.csv")
Index State Y2002 Y2003 Y2004 Y2005 Y2006 Y2007 \
0 A Alabama 1296530 1317711 1118631 1492583 1107408 1440134
1 A Alaska 1170302 1960378 1818085 1447852 1861639 1465841
2 A Arizona 1742027 1968140 1377583 1782199 1102568 1109382
3 A Arkansas 1485531 1994927 1119299 1947979 1669191 1801213
4 C California 1685349 1675807 1889570 1480280 1735069 1812546
Y2008 Y2009 Y2010 Y2011 Y2012 Y2013 Y2014 Y2015
0 1945229 1944173 1237582 1440756 1186741 1852841 1558906 1916661
1 1551826 1436541 1629616 1230866 1512804 1985302 1580394 1979143
2 1752886 1554330 1300521 1130709 1907284 1363279 1525866 1647724
3 1188104 1628980 1669295 1928238 1216675 1591896 1360959 1329341
4 1487315 1663809 1624509 1639670 1921845 1156536 1388461 1644607
获取变量名称
通过使用income.columns命令,您可以获取数据框的变量名称。
Index(['Index', 'State', 'Y2002', 'Y2003', 'Y2004', 'Y2005', 'Y2006', 'Y2007', 'Y2008', 'Y2009', 'Y2010', 'Y2011', 'Y2012', 'Y2013', 'Y2014', 'Y2015'],
dtype='object')
income.columns[0:2]返回前两列名称“Index”、“State”。在 python 中,索引从 0 开始。
了解变量类型
您可以使用dataFrameName.dtypes命令提取数据框中存储的变量类型信息。
income.dtypes
Index object
State object
Y2002 int64
Y2003 int64
Y2004 int64
Y2005 int64
Y2006 int64
Y2007 int64
Y2008 int64
Y2009 int64
Y2010 int64
Y2011 int64
Y2012 int64
Y2013 int64
Y2014 int64
Y2015 int64
dtype: object
这里的“对象”表示字符串或字符变量。' int64 '指的是数字变量(没有小数)。
要查看一个变量的变量类型(假设为“State”)而不是所有变量,您可以使用以下命令 -
income['State'].dtypes
它返回dtype('O')。 在这种情况下,“O”指的是对象,即作为字符的变量类型。
更改数据类型
Y2008 是一个整数。假设我们想将其转换为浮点数(带小数的数字变量),我们可以这样写:
income.Y2008 = income.Y2008.astype(float)
income.dtypes
Index object
State object
Y2002 int64
Y2003 int64
Y2004 int64
Y2005 int64
Y2006 int64
Y2007 int64
Y2008 float64
Y2009 int64
Y2010 int64
Y2011 int64
Y2012 int64
Y2013 int64
Y2014 int64
Y2015 int64
dtype: object
查看数据的维度或形状
income.shape
(51, 16)
51 是行数,16 是列数。
您还可以使用shape[0] 查看行数(类似于 R 中的 nrow()),使用shape[1] 查看列数(类似于 R 中的 ncol())。****
income.shape[0]
income.shape[1]
仅查看部分行
默认情况下,head() 显示前 5 行。如果我们想查看特定行数,可以在括号中提及。同样,tail() 函数默认显示最后 5 行。
income.head()
income.head(2) #shows first 2 rows.
income.tail()
income.tail(2) #shows last 2 rows
或者,可以使用以下任何命令来获取前五行。
income[0:5]
income.iloc[0:5]
定义分类变量
就像 R 中的 factors() 函数一样,我们可以使用“category” dtype 在 python 中包含分类变量。
s = pd.Series([1,2,3,1,2], dtype="category")
s
0 1
1 2
2 3
3 1
4 2
dtype: category
Categories (3, int64): [1, 2, 3]
提取唯一值
unique () 函数显示数据集中的唯一级别或类别。
income.Index.unique()
array(['A', 'C', 'D', ..., 'U', 'V', 'W'], dtype=object)
nunique ( ) 显示唯一值的数量。
income.Index.nunique()
它返回 19,因为索引列包含不同的 19 个值。
生成交叉表
pd.crosstab( ) 用于创建双变量频率分布。这里的双变量频率分布在Index和State列之间。
pd.crosstab(income.Index,income.State)
创建频率分布
income.Index选择“income”数据集的“Index”列,value_counts() 创建频率分布。默认情况下ascending = False即它将在顶部显示具有最大频率的“索引”。
income.Index.value_counts(ascending = True)
F 1
G 1
U 1
L 1
H 1
P 1
R 1
D 2
T 2
S 2
V 2
K 2
O 3
C 3
I 4
W 4
A 4
M 8
N 8
Name: Index, dtype: int64
绘制样品
income.sample() 用于从包含所有列的数据集中抽取随机样本。这里 n = 5 表示我们需要 5 列,frac = 0.1表示我们需要 10% 的数据作为样本。
income.sample(n = 5)
income.sample(frac = 0.1)
仅选择少数列
您可以通过多种方式选择特定列。以下两行代码都从收入数据框中选择状态变量。
income["State"]
income.State
要按名称选择多个列,您可以使用以下语法。
income[["Index","State","Y2008"]]
要仅选择特定的列和行,我们使用loc[ ] 或iloc[ ] 函数。要选择的索引或列作为列表传递。"Index":"Y2008" 表示选择Index到Y2008的所有列。
df.loc[ ] 的语法
df.loc[row_index , column_index]
income.loc[:,["Index","State","Y2008"]]
income.loc[0:2,["Index","State","Y2008"]] #Selecting rows with Index label 0 to 2 & columns
income.loc[:,"Index":"Y2008"] #Selecting consecutive columns
#In the above command both Index and Y2008 are included.
income.iloc[:,0:5] #Columns from 1 to 5 are included. 6th column not included
loc 和 iloc 的区别
loc考虑具有索引中特定标签的行(或列)。而iloc考虑索引中特定位置的行(或列),因此它只需要整数。
x = pd.DataFrame({"var1" : np.arange(1,20,2)}, index=[9,8,7,6,10, 1, 2, 3, 4, 5])
var1
9 1
8 3
7 5
6 7
10 9
1 11
2 13
3 15
4 17
5 19
- 定位码
-
x.loc[:3] Output: var1 9 1 8 3 7 5 6 7 10 9 1 11 2 13 3 15 - 代码本地代码
x.iloc[:3]
Output:
var1
9 1
8 3
7 5
重命名变量
我们为人们及其各自的星座信息创建了一个数据框“数据”。
data = pd.DataFrame({"A" : ["John","Mary","Julia","Kenny","Henry"], "B" : ["Libra","Capricorn","Aries","Scorpio","Aquarius"]})
data
A B
0 John Libra
1 Mary Capricorn
2 Julia Aries
3 Kenny Scorpio
4 Henry Aquarius
如果要重命名所有列,那么我们可以使用data.columns并分配新列名列表。
#Renaming all the variables.
data.columns = ['Names','Zodiac Signs']
Names Zodiac Signs 0 John Libra 1 Mary Capricorn 2 Julia Aries 3 Kenny Scorpio 4 Henry Aquarius
如果只有一些变量要重命名,那么我们可以使用rename() 函数,新名称以字典的形式传递。
#Renaming only some of the variables.
data.rename(columns = {"Names":"Cust_Name"},inplace = True)
Cust_Name Zodiac Signs 0 John Libra 1 Mary Capricorn 2 Julia Aries 3 Kenny Scorpio 4 Henry Aquarius
默认情况下,在 pandas inplace = False中,这意味着原始数据集中没有进行任何更改。因此,如果我们希望改变原始数据集,我们需要定义inplace = True。
假设我们只想替换列名列表中的特定字符,那么我们可以使用str.replace() 函数。例如,将包含“Y”的变量重命名为“Year”
income.columns = income.columns.str.replace('Y' , 'Year ')
income.columns
Index(['Index', 'State', 'Year 2002', 'Year 2003', 'Year 2004', 'Year 2005', 'Year 2006', 'Year 2007', 'Year 2008', 'Year 2009', 'Year 2010', 'Year 2011', 'Year 2012', 'Year 2013', 'Year 2014', 'Year 2015'],
dtype='object')
将数据框中的一列设置为索引
使用set_index("column name") 我们可以将索引设置为该列并删除该列。
income.set_index("Index",inplace = True)
income.head()
#Note that the indices have changed and Index column is now no more a column
income.columns
income.reset_index(inplace = True)
income.head()
reset_index() 告诉我们应该使用默认索引。
删除列和行
要删除列,我们使用drop() ,其中第一个参数是要删除的列的列表。
默认情况下axis = 0,这意味着操作应该水平、按行进行。要删除列,我们需要设置axis = 1.
income.drop('Index',axis = 1)
#Alternatively
income.drop("Index",axis = "columns")
income.drop(['Index','State'],axis = 1)
income.drop(0,axis = 0)
income.drop(0,axis = "index")
income.drop([0,1,2,3],axis = 0)
默认情况下 inplace = False 因此不会对原始数据集进行任何更改。axis = "columns" 和 axis = "index" 表示应分别删除列和行(索引)。
排序数据
为了对数据进行排序,部署了sort_values()函数。 默认情况下inplace = False和ascending = True。
income.sort_values("State",ascending = False)
income.sort_values("State",ascending = False,inplace = True)
income.Y2006.sort_values()
我们已经为 Index 复制了,因此我们需要首先按 Index 对数据帧进行排序,然后对于每个特定的索引,我们按 Y2002 对值进行排序
income.sort_values(["Index","Y2002"])
创建新变量
可以在数据集中对各种列 使用eval()算术运算。
income["difference"] = income.Y2008-income.Y2009
#Alternatively
income["difference2"] = income.eval("Y2008 - Y2009")
income.head()
Index State Y2002 Y2003 Y2004 Y2005 Y2006 Y2007 \
0 A Alabama 1296530 1317711 1118631 1492583 1107408 1440134
1 A Alaska 1170302 1960378 1818085 1447852 1861639 1465841
2 A Arizona 1742027 1968140 1377583 1782199 1102568 1109382
3 A Arkansas 1485531 1994927 1119299 1947979 1669191 1801213
4 C California 1685349 1675807 1889570 1480280 1735069 1812546
Y2008 Y2009 Y2010 Y2011 Y2012 Y2013 Y2014 Y2015 \
0 1945229.0 1944173 1237582 1440756 1186741 1852841 1558906 1916661
1 1551826.0 1436541 1629616 1230866 1512804 1985302 1580394 1979143
2 1752886.0 1554330 1300521 1130709 1907284 1363279 1525866 1647724
3 1188104.0 1628980 1669295 1928238 1216675 1591896 1360959 1329341
4 1487315.0 1663809 1624509 1639670 1921845 1156536 1388461 1644607
difference difference2
0 1056.0 1056.0
1 115285.0 115285.0
2 198556.0 198556.0
3 -440876.0 -440876.0
4 -176494.0 -176494.0
income.ratio = income.Y2008/income.Y2009
上面的命令不起作用,因此要创建新列,我们需要使用方括号。
我们也可以使用assign() 函数,但是这个命令不会对原始数据进行更改,因为没有 inplace 参数。因此我们需要将它保存在一个新的数据集中。
data = income.assign(ratio = (income.Y2008 / income.Y2009))
data.head()
查找描述性统计数据
describe( ) 用于查找一些统计数据,例如数字变量的平均值、最小值、四分位数等。
income.describe() #for numeric variables
Y2002 Y2003 Y2004 Y2005 Y2006 \
count 5.100000e+01 5.100000e+01 5.100000e+01 5.100000e+01 5.100000e+01
mean 1.566034e+06 1.509193e+06 1.540555e+06 1.522064e+06 1.530969e+06
std 2.464425e+05 2.641092e+05 2.813872e+05 2.671748e+05 2.505603e+05
min 1.111437e+06 1.110625e+06 1.118631e+06 1.122030e+06 1.102568e+06
25% 1.374180e+06 1.292390e+06 1.268292e+06 1.267340e+06 1.337236e+06
50% 1.584734e+06 1.485909e+06 1.522230e+06 1.480280e+06 1.531641e+06
75% 1.776054e+06 1.686698e+06 1.808109e+06 1.778170e+06 1.732259e+06
max 1.983285e+06 1.994927e+06 1.979395e+06 1.990062e+06 1.985692e+06
Y2007 Y2008 Y2009 Y2010 Y2011 \
count 5.100000e+01 5.100000e+01 5.100000e+01 5.100000e+01 5.100000e+01
mean 1.553219e+06 1.538398e+06 1.658519e+06 1.504108e+06 1.574968e+06
std 2.539575e+05 2.958132e+05 2.361854e+05 2.400771e+05 2.657216e+05
min 1.109382e+06 1.112765e+06 1.116168e+06 1.103794e+06 1.116203e+06
25% 1.322419e+06 1.254244e+06 1.553958e+06 1.328439e+06 1.371730e+06
50% 1.563062e+06 1.545621e+06 1.658551e+06 1.498662e+06 1.575533e+06
75% 1.780589e+06 1.779538e+06 1.857746e+06 1.639186e+06 1.807766e+06
max 1.983568e+06 1.990431e+06 1.993136e+06 1.999102e+06 1.992996e+06
Y2012 Y2013 Y2014 Y2015
count 5.100000e+01 5.100000e+01 5.100000e+01 5.100000e+01
mean 1.591135e+06 1.530078e+06 1.583360e+06 1.588297e+06
std 2.837675e+05 2.827299e+05 2.601554e+05 2.743807e+05
min 1.108281e+06 1.100990e+06 1.110394e+06 1.110655e+06
25% 1.360654e+06 1.285738e+06 1.385703e+06 1.372523e+06
50% 1.643855e+06 1.531212e+06 1.580394e+06 1.627508e+06
75% 1.866322e+06 1.725377e+06 1.791594e+06 1.848316e+06
max 1.988270e+06 1.994022e+06 1.990412e+06 1.996005e+06
对于字符或字符串变量,您可以编写include = ['object'] 。它将返回总计数、最大出现字符串及其频率
income.describe(include = ['object']) #Only for strings / objects
找出数据框每一列的具体描述性统计
income.mean()
income.median()
income.agg(["mean","median"])
agg( )使用求和、均值、中值、最小值、最大值等汇总函数执行聚合。
如何为特定列运行函数?
income.Y2008.mean()
income.Y2008.median()
income.Y2008.min()
income.loc[:,["Y2002","Y2008"]].max()
GroupBy 函数
为了按分类变量对数据进行分组,我们使用groupby() 函数,因此我们可以对每个类别进行操作。
income.groupby("Index")["Y2002","Y2003"].min()
Y2002 Y2003
Index
A 1170302 1317711
C 1343824 1232844
D 1111437 1268673
F 1964626 1468852
G 1929009 1541565
H 1461570 1200280
I 1353210 1438538
K 1509054 1290700
L 1584734 1110625
M 1221316 1149931
N 1395149 1114500
O 1173918 1334639
P 1320191 1446723
R 1501744 1942942
S 1159037 1150689
T 1520591 1310777
U 1771096 1195861
V 1134317 1163996
W 1677347 1380662
要运行多个汇总函数,我们可以使用agg( )用于聚合数据的函数。
income.groupby("Index")["Y2002","Y2003"].agg(["min","max","mean"])
以下命令查找 Y2002 的最小值和最大值以及 Y2003 的平均值
income.groupby("Index").agg({"Y2002": ["min","max"],"Y2003" : "mean"})
Y2002 Y2003
min max mean
Index
A 1170302 1742027 1810289.000
C 1343824 1685349 1595708.000
D 1111437 1330403 1631207.000
F 1964626 1964626 1468852.000
G 1929009 1929009 1541565.000
H 1461570 1461570 1200280.000
I 1353210 1776918 1536164.500
K 1509054 1813878 1369773.000
L 1584734 1584734 1110625.000
M 1221316 1983285 1535717.625
N 1395149 1885081 1382499.625
O 1173918 1802132 1569934.000
P 1320191 1320191 1446723.000
R 1501744 1501744 1942942.000
S 1159037 1631522 1477072.000
T 1520591 1811867 1398343.000
U 1771096 1771096 1195861.000
V 1134317 1146902 1498122.500
W 1677347 1977749 1521118.500
为了rename之后的列groupby,您可以使用元组。请参阅下面的代码。
income.groupby("Index").agg({"Y2002" : [("Y2002_min","min"),("Y2002_max","max")],
"Y2003" : [("Y2003_mean","mean")]})
重命名列也可以通过以下方法完成。
dt = income.groupby("Index").agg({"Y2002": ["min","max"],"Y2003" : "mean"})
dt.columns = ['Y2002_min', 'Y2002_max', 'Y2003_mean']
Groupby 超过 1 列
income.groupby(["Index", "State"]).agg({"Y2002": ["min","max"],"Y2003" : "mean"})
默认情况下,选项as_index=True在 groupby 中启用,这意味着您在 groupby 中使用的列将成为新数据框中的索引。要禁用它,您可以将其设置为 False ,它将您在 groupby 中使用的变量存储在新数据框中的不同列中。
dt = income.groupby(["Index","State"], as_index=False)["Y2002","Y2003"].min()
过滤
要仅过滤索引为“A”的那些行,我们编写:
income[income.Index == "A"]
#Alternatively
income.loc[income.Index == "A",:]
Index State Y2002 Y2003 Y2004 Y2005 Y2006 Y2007 \
0 A Alabama 1296530 1317711 1118631 1492583 1107408 1440134
1 A Alaska 1170302 1960378 1818085 1447852 1861639 1465841
2 A Arizona 1742027 1968140 1377583 1782199 1102568 1109382
3 A Arkansas 1485531 1994927 1119299 1947979 1669191 1801213
Y2008 Y2009 Y2010 Y2011 Y2012 Y2013 Y2014 Y2015
0 1945229 1944173 1237582 1440756 1186741 1852841 1558906 1916661
1 1551826 1436541 1629616 1230866 1512804 1985302 1580394 1979143
2 1752886 1554330 1300521 1130709 1907284 1363279 1525866 1647724
3 1188104 1628980 1669295 1928238 1216675 1591896 1360959 1329341
要选择索引为“A”的州:
income.loc[income.Index == "A","State"]
income.loc[income.Index == "A",:].State
过滤索引为“A”且收入为 2002 > 1500000 的行
income.loc[(income.Index == "A") & (income.Y2002 > 1500000),:]
要过滤索引为“A”或“W”的行,我们可以使用isin() 函数:
income.loc[(income.Index == "A") | (income.Index == "W"),:]
#Alternatively.
income.loc[income.Index.isin(["A","W"]),:]
Index State Y2002 Y2003 Y2004 Y2005 Y2006 Y2007 \
0 A Alabama 1296530 1317711 1118631 1492583 1107408 1440134
1 A Alaska 1170302 1960378 1818085 1447852 1861639 1465841
2 A Arizona 1742027 1968140 1377583 1782199 1102568 1109382
3 A Arkansas 1485531 1994927 1119299 1947979 1669191 1801213
47 W Washington 1977749 1687136 1199490 1163092 1334864 1621989
48 W West Virginia 1677347 1380662 1176100 1888948 1922085 1740826
49 W Wisconsin 1788920 1518578 1289663 1436888 1251678 1721874
50 W Wyoming 1775190 1498098 1198212 1881688 1750527 1523124
Y2008 Y2009 Y2010 Y2011 Y2012 Y2013 Y2014 Y2015
0 1945229 1944173 1237582 1440756 1186741 1852841 1558906 1916661
1 1551826 1436541 1629616 1230866 1512804 1985302 1580394 1979143
2 1752886 1554330 1300521 1130709 1907284 1363279 1525866 1647724
3 1188104 1628980 1669295 1928238 1216675 1591896 1360959 1329341
47 1545621 1555554 1179331 1150089 1775787 1273834 1387428 1377341
48 1238174 1539322 1539603 1872519 1462137 1683127 1204344 1198791
49 1980167 1901394 1648755 1940943 1729177 1510119 1701650 1846238
50 1587602 1504455 1282142 1881814 1673668 1994022 1204029 1853858
或者,我们可以使用query( )函数,它也消除了在提及列时指定数据框的需要,并让您编写我们的过滤条件:
income.query('Y2002>1700000 & Y2003 > 1500000')
处理缺失值
我们创建一个名为“crops”的新数据框,并通过导入numpy使用 np.nan 创建一个 NaN 值。
import numpy as np
mydata = {'Crop': ['Rice', 'Wheat', 'Barley', 'Maize'],
'Yield': [1010, 1025.2, 1404.2, 1251.7],
'cost' : [102, np.nan, 20, 68]}
crops = pd.DataFrame(mydata)
crops
如果值为 NaN,isnull() 返回 True,而notnull()返回 False。
crops.isnull() #same as is.na in R
crops.notnull() #opposite of previous command.
crops.isnull().sum() #No. of missing values.
crops.cost.isnull() 首先对数据帧中的“成本”进行子集化,并返回一个带有 isnull() 的逻辑向量
crops[crops.cost.isnull()] #shows the rows with NAs.
crops[crops.cost.isnull()].Crop #shows the rows with NAs in crops.Crop
crops[crops.cost.notnull()].Crop #shows the rows without NAs in crops.Crop
要删除任何行中包含缺失值的所有行,我们使用dropna(how = "any") 。默认情况下inplace = False。如果how = "all" 表示如果该行中的所有元素都丢失则删除该行
crops.dropna(how = "any").shape
crops.dropna(how = "all").shape
如果缺少“产量”或“成本”中的任何一个,要删除 NaN,我们使用子集参数并传递一个列表:
crops.dropna(subset = ['Yield',"cost"],how = 'any').shape
crops.dropna(subset = ['Yield',"cost"],how = 'all').shape
用列名中的“UNKNOWN”子属性替换缺失值。
crops['cost'].fillna(value = "UNKNOWN",inplace = True)
crops
处理重复项
我们创建了一个包含项目及其各自价格的新数据框。
data = pd.DataFrame({"Items" : ["TV","Washing Machine","Mobile","TV","TV","Washing Machine"], "Price" : [10000,50000,20000,10000,10000,40000]})
data
Items Price
0 TV 10000
1 Washing Machine 50000
2 Mobile 20000
3 TV 10000
4 TV 10000
5 Washing Machine 40000
duplicated() 返回一个逻辑向量,当遇到 duplicated 时返回 True。
data.loc[data.duplicated(),:]
data.loc[data.duplicated(keep = "first"),:]
默认情况下keep = 'first' 即第一次出现被认为是一个唯一值,它的重复被认为是重复的。
如果keep = "last" 最后一次出现被认为是一个唯一值,它的所有重复都被认为是重复的。
data.loc[data.duplicated(keep = "last"),:] #last entries are not there,indices have changed.
如果keep = "False" 然后它认为重复观察的所有出现都是重复的。
data.loc[data.duplicated(keep = False),:] #all the duplicates, including unique are shown.
要删除重复项,drop_duplicates与默认 inplace = False 一起使用 , keep = 'first' or 'last' or 'False' 具有与 duplicated( ) 中的相应含义
data.drop_duplicates(keep = "first")
data.drop_duplicates(keep = "last")
data.drop_duplicates(keep = False,inplace = True) #by default inplace = False
创建假人
现在我们将考虑iris 数据集。
iris = pd.read_csv("C:\Users\Hp\Desktop\work\Python\Basics\pandas\iris.csv")
iris.head()
Sepal.Length Sepal.Width Petal.Length Petal.Width Species 0 5.1 3.5 1.4 0.2 setosa 1 4.9 3.0 1.4 0.2 setosa 2 4.7 3.2 1.3 0.2 setosa 3 4.6 3.1 1.5 0.2 setosa 4 5.0 3.6 1.4 0.2 setosa
map( ) 函数用于匹配值并在自动创建的新系列中替换它们。
iris["setosa"] = iris.Species.map({"setosa" : 1,"versicolor":0, "virginica" : 0})
iris.head()
要创建假人,使用get_dummies() 。 iris.Species.prefix = "Species" 向创建的新系列添加前缀“Species”。
pd.get_dummies(iris.Species,prefix = "Species")
pd.get_dummies(iris.Species,prefix = "Species").iloc[:,0:1] #1 is not included
species_dummies = pd.get_dummies(iris.Species,prefix = "Species").iloc[:,0:]
使用concat() 函数,我们可以连接多个系列或数据帧。axis = 1表示它们应该按列连接。
iris = pd.concat([iris,species_dummies],axis = 1)
iris.head()
Sepal.Length Sepal.Width Petal.Length Petal.Width Species \ 0 5.1 3.5 1.4 0.2 setosa 1 4.9 3.0 1.4 0.2 setosa 2 4.7 3.2 1.3 0.2 setosa 3 4.6 3.1 1.5 0.2 setosa 4 5.0 3.6 1.4 0.2 setosa Species_setosa Species_versicolor Species_virginica 0 1 0 0 1 1 0 0 2 1 0 0 3 1 0 0 4 1 0 0
通常,对于具有“n”类别的变量,我们创建“n-1”个虚拟变量,因此要删除第一个“虚拟”列,我们编写drop_first = True
pd.get_dummies(iris,columns = ["Species"],drop_first = True).head()
排行
要创建所有等级的数据框,我们使用rank()
iris.rank()
按特定变量排名
假设我们想按升序排列不同物种的 Sepal.Length:
iris['Rank2'] = iris['Sepal.Length'].groupby(iris["Species"]).rank(ascending=1)
iris.head()
计算累计和
使用cumsum( ) 函数我们可以获得累积和
iris['cum_sum'] = iris["Sepal.Length"].cumsum()
iris.head()
一个变量的累计和
为了找到不同物种萼片长度的累积和,我们使用groupby( ) 然后使用cumsum( )
iris["cumsum2"] = iris.groupby(["Species"])["Sepal.Length"].cumsum()
iris.head()
计算百分位数。
可以使用quantile( )获得各种分位数
iris.quantile(0.5)
iris.quantile([0.1,0.2,0.5])
iris.quantile(0.55)
否则在 Python 中
我们创建了一个包含学生姓名及其各自星座的新数据框。
students = pd.DataFrame({'Names': ['John','Mary','Henry','Augustus','Kenny'],
'Zodiac Signs': ['Aquarius','Libra','Gemini','Pisces','Virgo']})
def name(row):
if row["Names"] in ["John","Henry"]:
return "yes"
else:
return "no"
students['flag'] = students.apply(name, axis=1)
students
python 中的函数是使用 block 关键字定义的def ,后跟函数的名称作为块的名称。apply( ) 函数沿着数据帧的行或列应用函数。
Note :如果使用简单的“if else”,我们需要注意缩进。Python 不涉及循环和 if else 的大括号。
输出
Names Zodiac Signs flag
0 John Aquarius yes
1 Mary Libra no
2 Henry Gemini yes
3 Augustus Pisces no
4 Kenny Virgo no
或者,通过导入 numpy 我们可以使用np.where。第一个参数是要评估的条件,第二个参数是条件为 True 时的值,最后一个参数定义条件评估返回 False 时的值。
import numpy as np
students['flag'] = np.where(students['Names'].isin(['John','Henry']), 'yes', 'no')
students
多个条件:If Else-if Else
def mname(row):
if row["Names"] == "John" and row["Zodiac Signs"] == "Aquarius" :
return "yellow"
elif row["Names"] == "Mary" and row["Zodiac Signs"] == "Libra" :
return "blue"
elif row["Zodiac Signs"] == "Pisces" :
return "blue"
else:
return "black"
students['color'] = students.apply(mname, axis=1)
students
如果评估为 True,我们创建条件列表及其各自的值,并使用np.select,其中默认值是所有条件为 False 时的值
conditions = [
(students['Names'] == 'John') & (students['Zodiac Signs'] == 'Aquarius'),
(students['Names'] == 'Mary') & (students['Zodiac Signs'] == 'Libra'),
(students['Zodiac Signs'] == 'Pisces')]
choices = ['yellow', 'blue', 'purple']
students['color'] = np.select(conditions, choices, default='black')
students
Names Zodiac Signs flag color
0 John Aquarius yes yellow
1 Mary Libra no blue
2 Henry Gemini yes black
3 Augustus Pisces no purple
4 Kenny Virgo no black
仅选择数字或分类列
为了包含数字列,我们使用select_dtypes()
data1 = iris.select_dtypes(include=[np.number])
data1.head()
_get_numeric_data还提供了仅选择数字列的实用程序。
data3 = iris._get_numeric_data()
data3.head(3)
Sepal.Length Sepal.Width Petal.Length Petal.Width cum_sum cumsum2 0 5.1 3.5 1.4 0.2 5.1 5.1 1 4.9 3.0 1.4 0.2 10.0 10.0 2 4.7 3.2 1.3 0.2 14.7 14.7
用于选择分类变量
data4 = iris.select_dtypes(include = ['object'])
data4.head(2)
Species 0 setosa 1 setosa
拼接
我们创建了 2 个包含学生详细信息的数据框:
students = pd.DataFrame({'Names': ['John','Mary','Henry','Augustus','Kenny'],
'Zodiac Signs': ['Aquarius','Libra','Gemini','Pisces','Virgo']})
students2 = pd.DataFrame({'Names': ['John','Mary','Henry','Augustus','Kenny'],
'Marks' : [50,81,98,25,35]})
使用pd.concat( ) 函数我们可以加入 2 个数据帧:
data = pd.concat([students,students2]) #by default axis = 0
> ```
> ```
> Marks Names Zodiac Signs
> 0 NaN John Aquarius
> 1 NaN Mary Libra
> 2 NaN Henry Gemini
> 3 NaN Augustus Pisces
> 4 NaN Kenny Virgo
> 0 50.0 John NaN
> 1 81.0 Mary NaN
> 2 98.0 Henry NaN
> 3 25.0 Augustus NaN
> 4 35.0 Kenny NaN
> ```
因此,默认情况下,`axis = 0`新数据框将按行添加。如果列不存在,则在其中一个数据框中创建 NaN。为了明智地加入专栏,我们设置`axis = 1`
> ```
> data = pd.concat([students,students2],axis = 1)
> data
> ```
> ```
> Names Zodiac Signs Marks Names
> 0 John Aquarius 50 John
> 1 Mary Libra 81 Mary
> 2 Henry Gemini 98 Henry
> 3 Augustus Pisces 25 Augustus
> 4 Kenny Virgo 35 Kenny
> ```
使用**append**函数,我们可以按行连接数据帧
> ```
> students.append(students2) #for rows
> ```
或者,我们可以创建两个数据框的**字典,并可以使用** **pd.concat**按行连接数据框
> ```
> classes = {'x': students, 'y': students2}
> result = pd.concat(classes)
> result
> ```
> ```
> Marks Names Zodiac Signs
> x 0 NaN John Aquarius
> 1 NaN Mary Libra
> 2 NaN Henry Gemini
> 3 NaN Augustus Pisces
> 4 NaN Kenny Virgo
> y 0 50.0 John NaN
> 1 81.0 Mary NaN
> 2 98.0 Henry NaN
> 3 25.0 Augustus NaN
> 4 35.0 Kenny NaN
> ```
**在公共变量的基础上合并或加入。**
我们采用 2 个具有不同观测值的数据帧:
> ```
> students = pd.DataFrame({'Names': ['John','Mary','Henry','Augustus','Kenny'],
> 'Zodiac Signs': ['Aquarius','Libra','Gemini','Pisces','Virgo']})
> students2 = pd.DataFrame({'Names': ['John','Mary','Henry','Augustus','Kenny'],
> 'Marks' : [50,81,98,25,35]})
> ```
使用**pd.merge**我们可以加入两个数据框。**on = 'Names'** 表示要组合数据框的公共变量是 'Names'
> ```
> result = pd.merge(students, students2, on='Names') #it only takes intersections
> result
> ```
> ```
> Names Zodiac Signs Marks
> 0 John Aquarius 50
> 1 Mary Libra 81
> 2 Henry Gemini 98
> ```
默认情况下**how = "inner"** 因此它只需要两个数据框中的公共元素。如果您想要两个数据框中的所有元素,请设置**how = "outer"**
> ```
> result = pd.merge(students, students2, on='Names',how = "outer") #it only takes unions
> result
> ```
> ```
> Names Zodiac Signs Marks
> 0 John Aquarius 50.0
> 1 Mary Libra 81.0
> 2 Henry Gemini 98.0
> 3 Maria Capricorn NaN
> 4 Augustus NaN 25.0
> 5 Kenny NaN 35.0
> ```
只取交点和左边的所有值 df set how = 'left'
> ```
> result = pd.merge(students, students2, on='Names',how = "left")
> result
> ```
> ```
> Names Zodiac Signs Marks
> 0 John Aquarius 50.0
> 1 Mary Libra 81.0
> 2 Henry Gemini 98.0
> 3 Maria Capricorn NaN
> ```
类似地,**how = 'right'** 仅采用交叉点和右 df 中的所有值。
> ```
> result = pd.merge(students, students2, on='Names',how = "right",indicator = True)
> result
> ```
> ```
> Names Zodiac Signs Marks _merge
> 0 John Aquarius 50 both
> 1 Mary Libra 81 both
> 2 Henry Gemini 98 both
> 3 Augustus NaN 25 right_only
> 4 Kenny NaN 35 right_only
> ```
indicator = True创建一个列,用于指示值是否同时存在于数据帧或左数据帧或右数据帧中。