配色: 字号:
Python 数据操作教程(最佳Pandas教程通过 50 个示例学习)
2023-07-05 | 阅:  转:  |  分享 
  
?Pandas 是 Python 中最受欢迎的软件包之一,广泛用于数据操作。它是一个非常强大且用途广泛的软件包,使数据清理和整理变得更加轻松
愉快。Pandas 库对 Python 社区做出了巨大贡献,它使 Python 成为数据科学和分析领域的顶级编程语言之一。它已成为
数据分析师和科学家进行数据分析和操作的首选。?什么是熊猫包?Pandas 包具有许多功能,这些功能是数据处理和操作的本质。简而言之
,它可以为您执行以下任务——创建类似于 R 的数据框和 Excel 电子表格的结构化数据集。从 CSV、TXT、XLSX、SQL
数据库、R 等各种来源读取数据。从数据集中选择特定的行或列按升序或降序排列数据根据某些条件过滤数据按分类变量汇总数据将数据重塑为宽
格式或长格式时间序列分析合并和连接两个数据集遍历数据集的行以 CSV 或 Excel 格式写入或导出数据数据集:在本教程中,我们将
使用两个数据集:''income''和''iris''。''income'' data?: 该数据包含各米国各州从2002年到2015年的收入
。该数据集包含51个观测值和16个变量。https://github.com/deepanshu88/Datasets/raw/m
aster/UploadedFiles/income.csv下载链接''iris'' 数据:它包含 150 个观测值和 5 个变量。我
们有 3 种花(每种 50 朵花),所有花的萼片长度和宽度以及花瓣长度和宽度都已给出。https://github.com/dee
panshu88/Datasets/raw/master/UploadedFiles/iris.csv下载链接?要记住的重要熊猫功
能以下是常见任务以及 pandas 函数的列表。公用事业功能提取列名称df.列选择前 2 行df.iloc[:2]选择前 2 列d
f.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_du
mmies( )排行df.rank( )累计金额df.cumsum( )分位数df.分位数()选择数值变量df.select_dt
ypes()连接两个数据帧pd.concat()基于公共变量合并pd.合并()导入熊猫库您需要先导入或加载 Pandas 库才能使
用它。“Importing a library”就是把它加载到内存中,然后你就可以使用它了。运行以下代码导入 pandas 库:i
mport pandas as pd“pd”是别名或缩写,将用作访问或调用 pandas 函数的快捷方式。要访问 pandas 库
中的函数,您只需在每次需要应用时键入pd.function?而不是??pandas.function 。导入数据集要从 CSV 文
件读取或导入数据,可以使用read_csv() 函数。在该函数中,您需要指定 CSV 文件的文件位置。income = pd.re
ad_csv("C:\\Users\\Hp\\Python\\Basics\\income.csv") Index S
tate Y2002 Y2003 Y2004 Y2005 Y2006 Y2007 \0
A Alabama 1296530 1317711 1118631 1492583 1107408 144
01341 A Alaska 1170302 1960378 1818085 1447852 1861
639 14658412 A Arizona 1742027 1968140 1377583 17821
99 1102568 11093823 A Arkansas 1485531 1994927 111929
9 1947979 1669191 18012134 C California 1685349 1675807
1889570 1480280 1735069 1812546 Y2008 Y2009 Y2010 Y
2011 Y2012 Y2013 Y2014 Y2015 0 1945229 1944173 12
37582 1440756 1186741 1852841 1558906 1916661 1 1551826 1
436541 1629616 1230866 1512804 1985302 1580394 1979143 2
1752886 1554330 1300521 1130709 1907284 1363279 1525866 16
47724 3 1188104 1628980 1669295 1928238 1216675 1591896 1
360959 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'', ''Y2
013'', ''Y2014'', ''Y2015''], dtype=''object'')income.columns[0:2]返回前两列名
称“Index”、“State”。在 python 中,索引从 0 开始。了解变量类型您可以使用dataFrameName.dty
pes命令提取数据框中存储的变量类型信息。income.dtypes?Index objectState object
Y2002 int64Y2003 int64Y2004 int64Y2005 int64Y2006
int64Y2007 int64Y2008 int64Y2009 int64Y2010
int64Y2011 int64Y2012 int64Y2013 int64Y2014 int64
Y2015 int64dtype: object这里的“对象”表示字符串或字符变量。''?int64?''指的是数字变量(没有
小数)。要查看一个变量的变量类型(假设为“State”)而不是所有变量,您可以使用以下命令 -income[''State''].dt
ypes它返回dtype(''O'')。在这种情况下,“O”指的是对象,即作为字符的变量类型。更改数据类型Y2008 是一个整数。假设
我们想将其转换为浮点数(带小数的数字变量),我们可以这样写:income.Y2008 = income.Y2008.astype(
float)income.dtypesIndex objectState objectY2002 int
64Y2003 int64Y2004 int64Y2005 int64Y2006 int6
4Y2007 int64Y2008 float64Y2009 int64Y2010 int64
Y2011 int64Y2012 int64Y2013 int64Y2014 int64Y
2015 int64dtype: 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()incom
e.head(2) #shows first 2 rows.income.tail() income.tail(2) #sho
ws 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")s0 11 22 33
14 2dtype: categoryCategories (3, int64): [1, 2, 3]提取唯一值uni
que?()函数显示数据集中的唯一级别或类别。income.Index.unique()array([''A'', ''C'', ''D'',
..., ''U'', ''V'', ''W''], dtype=object)nunique?( )显示唯一值的数量。income.Ind
ex.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 1G 1U 1L 1H 1P 1R 1D
2T 2S 2V 2K 2O 3C 3I 4W 4A 4M 8N
8Name: 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[["I
ndex","State","Y2008"]]要仅选择特定的列和行,我们使用loc[ ]或iloc[ ]函数。要选择的索引或列作为
列表传递。"Index":"Y2008" 表示选择Index到Y2008的所有列。df.loc[ ] 的语法df.loc[row_
index , column_index]income.loc[:,["Index","State","Y2008"]]incom
e.loc[0:2,["Index","State","Y2008"]]? #Selecting rows with Index
label 0 to 2 & columnsincome.loc[:,"Index":"Y2008"]? #Selecting c
onsecutive columns#In the above command both Index and Y2008 are
included.income.iloc[:,0:5]? #Columns from 1 to 5 are included. 6
th column not includedloc 和 iloc 的区别loc考虑具有索引中特定标签的行(或列)。而iloc考虑索
引中特定位置的行(或列),因此它只需要整数。x = pd.DataFrame({"var1" : np.arange(1,20,2
)}, index=[9,8,7,6,10, 1, 2, 3, 4, 5]) var19 18 37
56 710 91 112 133 154 175 19定位码x.lo
c[:3]Output: var19 18 37 56 710 91 11
2 133 15代码本地代码x.iloc[:3]Output: var19 18 37 5
重命名变量?我们为人们及其各自的星座信息创建了一个数据框“数据”。data = pd.DataFrame({"A" : ["Joh
n","Mary","Julia","Kenny","Henry"], "B" : ["Libra","Capricorn","A
ries","Scorpio","Aquarius"]})data? A B0 John Libr
a1 Mary Capricorn2 Julia Aries3 Kenny Scorpio4 Henr
y Aquarius如果要重命名所有列,那么我们可以使用data.columns并分配新列名列表。#Renaming all
the variables.data.columns = [''Names'',''Zodiac Signs''] Names Zodia
c Signs0 John Libra1 Mary Capricorn2 Julia
Aries3 Kenny Scorpio4 Henry Aquarius如果只有一些变量要重命名,那么我们可
以使用rename()函数,新名称以字典的形式传递。#Renaming only some of the variables.da
ta.rename(columns = {"Names":"Cust_Name"},inplace = True) Cust_N
ame Zodiac Signs0 John Libra1 Mary Capricorn2
Julia Aries3 Kenny Scorpio4 Henry Aq
uarius默认情况下,在 pandas?inplace = False中,这意味着原始数据集中没有进行任何更改。因此,如果我们希
望改变原始数据集,我们需要定义inplace = True。假设我们只想替换列名列表中的特定字符,那么我们可以使用str.repl
ace()函数。例如,将包含“Y”的变量重命名为“Year”income.columns = income.columns.str
.replace(''Y'' , ''Year '')income.columnsIndex([''Index'', ''State'', ''Ye
ar 2002'', ''Year 2003'', ''Year 2004'', ''Year 2005'', ''Year 2006'', ''Ye
ar 2007'', ''Year 2008'', ''Year 2009'', ''Year 2010'', ''Year 2011'', ''Ye
ar 2012'', ''Year 2013'', ''Year 2014'', ''Year 2015''], dtype=''object'')
将数据框中的一列设置为索引使用set_index("column name")我们可以将索引设置为该列并删除该列。income.s
et_index("Index",inplace = True)income.head()#Note that the indic
es have changed and Index column is now no more a columnincome.co
lumnsincome.reset_index(inplace = True)income.head()reset_index()
告诉我们应该使用默认索引。删除列和行要删除列,我们使用drop(),其中第一个参数是要删除的列的列表。默认情况下axis = 0,
这意味着操作应该水平、按行进行。要删除列,我们需要设置axis = 1.income.drop(''Index'',axis = 1)
#Alternativelyincome.drop("Index",axis = "columns")income.drop([''
Index'',''State''],axis = 1)income.drop(0,axis = 0)income.drop(0,axi
s = "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
#Alternativelyincome["difference2"] = income.eval("Y2008 - Y2009"
)income.head() Index State Y2002 Y2003 Y2004 Y2
005 Y2006 Y2007 \0 A Alabama 1296530 1317711 11
18631 1492583 1107408 14401341 A Alaska 1170302 196
0378 1818085 1447852 1861639 14658412 A Arizona 1742
027 1968140 1377583 1782199 1102568 11093823 A Arkans
as 1485531 1994927 1119299 1947979 1669191 18012134 C
California 1685349 1675807 1889570 1480280 1735069 1812546
Y2008 Y2009 Y2010 Y2011 Y2012 Y2013 Y2014 Y2
015 \0 1945229.0 1944173 1237582 1440756 1186741 1852841
1558906 19166611 1551826.0 1436541 1629616 1230866 1512804
1985302 1580394 19791432 1752886.0 1554330 1300521 1130709
1907284 1363279 1525866 16477243 1188104.0 1628980 166929
5 1928238 1216675 1591896 1360959 13293414 1487315.0 16638
09 1624509 1639670 1921845 1156536 1388461 1644607 differen
ce difference2 0 1056.0 1056.0 1 115285.0 11
5285.0 2 198556.0 198556.0 3 -440876.0 -440876.0 4
-176494.0 -176494.0 income.ratio = income.Y2008/income.Y20
09上面的命令不起作用,因此要创建新列,我们需要使用方括号。我们也可以使用assign()函数,但是这个命令不会对原始数据进行更改
,因为没有 inplace 参数。因此我们需要将它保存在一个新的数据集中。data = income.assign(ratio =
(income.Y2008 / income.Y2009))data.head()查找描述性统计数据describe( )用于查
找一些统计数据,例如数字变量的平均值、最小值、四分位数等。income.describe() #for numeric varia
bles Y2002 Y2003 Y2004 Y2005 Y200
6 \count 5.100000e+01 5.100000e+01 5.100000e+01 5.100000e+01
5.100000e+01mean 1.566034e+06 1.509193e+06 1.540555e+06 1.
522064e+06 1.530969e+06std 2.464425e+05 2.641092e+05 2.8138
72e+05 2.671748e+05 2.505603e+05min 1.111437e+06 1.110625e+
06 1.118631e+06 1.122030e+06 1.102568e+0625% 1.374180e+06
1.292390e+06 1.268292e+06 1.267340e+06 1.337236e+0650% 1.58
4734e+06 1.485909e+06 1.522230e+06 1.480280e+06 1.531641e+067
5% 1.776054e+06 1.686698e+06 1.808109e+06 1.778170e+06 1.7
32259e+06max 1.983285e+06 1.994927e+06 1.979395e+06 1.99006
2e+06 1.985692e+06 Y2007 Y2008 Y2009 Y20
10 Y2011 \count 5.100000e+01 5.100000e+01 5.100000e+0
1 5.100000e+01 5.100000e+01mean 1.553219e+06 1.538398e+06 1
.658519e+06 1.504108e+06 1.574968e+06std 2.539575e+05 2.958
132e+05 2.361854e+05 2.400771e+05 2.657216e+05min 1.109382e
+06 1.112765e+06 1.116168e+06 1.103794e+06 1.116203e+0625%
1.322419e+06 1.254244e+06 1.553958e+06 1.328439e+06 1.371730
e+0650% 1.563062e+06 1.545621e+06 1.658551e+06 1.498662e+06
1.575533e+0675% 1.780589e+06 1.779538e+06 1.857746e+06 1.
639186e+06 1.807766e+06max 1.983568e+06 1.990431e+06 1.9931
36e+06 1.999102e+06 1.992996e+06 Y2012 Y2013 Y2
014 Y2015 count 5.100000e+01 5.100000e+01 5.100000e+0
1 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.1
10655e+06 25% 1.360654e+06 1.285738e+06 1.385703e+06 1.372
523e+06 50% 1.643855e+06 1.531212e+06 1.580394e+06 1.62750
8e+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+0
6对于字符或字符串变量,您可以编写include = [''object'']。它将返回总计数、最大出现字符串及其频率income.d
escribe(include = [''object'']) #Only for strings / objects找出数据框每一列
的具体描述性统计income.mean()income.median()income.agg(["mean","median"])
agg( )使用求和、均值、中值、最小值、最大值等汇总函数执行聚合。如何为特定列运行函数?income.Y2008.mean()i
ncome.Y2008.median()income.Y2008.min()income.loc[:,["Y2002","Y200
8"]].max()GroupBy 函数为了按分类变量对数据进行分组,我们使用groupby()函数,因此我们可以对每个类别进行操
作。income.groupby("Index")["Y2002","Y2003"].min() Y2002 Y2003In
dexA 1170302 1317711C 1343824 1232844D 1111437
1268673F 1964626 1468852G 1929009 1541565H 14615
70 1200280I 1353210 1438538K 1509054 1290700L 1
584734 1110625M 1221316 1149931N 1395149 1114500O
1173918 1334639P 1320191 1446723R 1501744 1942942
S 1159037 1150689T 1520591 1310777U 1771096 119
5861V 1134317 1163996W 1677347 1380662要运行多个汇总函数,我们可以使
用agg( )用于聚合数据的函数。income.groupby("Index")["Y2002","Y2003"].agg(["m
in","max","mean"])以下命令查找 Y2002 的最小值和最大值以及 Y2003 的平均值income.groupb
y("Index").agg({"Y2002": ["min","max"],"Y2003" : "mean"}) Y2002
Y2003 min max meanIndexA 1170302
1742027 1810289.000C 1343824 1685349 1595708.000D
1111437 1330403 1631207.000F 1964626 1964626 1468852.000
G 1929009 1929009 1541565.000H 1461570 1461570 1200
280.000I 1353210 1776918 1536164.500K 1509054 181387
8 1369773.000L 1584734 1584734 1110625.000M 1221316
1983285 1535717.625N 1395149 1885081 1382499.625O 1
173918 1802132 1569934.000P 1320191 1320191 1446723.000R
1501744 1501744 1942942.000S 1159037 1631522 14770
72.000T 1520591 1811867 1398343.000U 1771096 1771096
1195861.000V 1134317 1146902 1498122.500W 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" : "m
ean"})dt.columns = [''Y2002_min'', ''Y2002_max'', ''Y2003_mean'']Groupb
y 超过 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=Fa
lse)["Y2002","Y2003"].min()过滤要仅过滤索引为“A”的那些行,我们编写:income[income.In
dex == "A"]#Alternativelyincome.loc[income.Index == "A",:] Index
State Y2002 Y2003 Y2004 Y2005 Y2006 Y2007
\0 A Alabama 1296530 1317711 1118631 1492583 1107408
14401341 A Alaska 1170302 1960378 1818085 1447852 186
1639 14658412 A Arizona 1742027 1968140 1377583 178219
9 1102568 11093823 A Arkansas 1485531 1994927 1119299
1947979 1669191 1801213 Y2008 Y2009 Y2010 Y2011 Y20
12 Y2013 Y2014 Y2015 0 1945229 1944173 1237582 1440
756 1186741 1852841 1558906 1916661 1 1551826 1436541 162
9616 1230866 1512804 1985302 1580394 1979143 2 1752886 15
54330 1300521 1130709 1907284 1363279 1525866 1647724 3 1
188104 1628980 1669295 1928238 1216675 1591896 1360959 132
9341 要选择索引为“A”的州:income.loc[income.Index == "A","State"]income.lo
c[income.Index == "A",:].State过滤索引为“A”且收入为 2002 > 1500000 的行incom
e.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 Y200
5 Y2006 Y2007 \0 A Alabama 1296530 1317711
1118631 1492583 1107408 14401341 A Alaska 117030
2 1960378 1818085 1447852 1861639 14658412 A Ari
zona 1742027 1968140 1377583 1782199 1102568 11093823
A Arkansas 1485531 1994927 1119299 1947979 1669191 18
0121347 W Washington 1977749 1687136 1199490 1163092
1334864 162198948 W West Virginia 1677347 1380662 11761
00 1888948 1922085 174082649 W Wisconsin 1788920 15
18578 1289663 1436888 1251678 172187450 W Wyoming
1775190 1498098 1198212 1881688 1750527 1523124 Y2008 Y2
009 Y2010 Y2011 Y2012 Y2013 Y2014 Y2015 0 19
45229 1944173 1237582 1440756 1186741 1852841 1558906 1916
661 1 1551826 1436541 1629616 1230866 1512804 1985302 15
80394 1979143 2 1752886 1554330 1300521 1130709 1907284
1363279 1525866 1647724 3 1188104 1628980 1669295 1928238
1216675 1591896 1360959 1329341 47 1545621 1555554 11793
31 1150089 1775787 1273834 1387428 1377341 48 1238174 153
9322 1539603 1872519 1462137 1683127 1204344 1198791 49 1
980167 1901394 1648755 1940943 1729177 1510119 1701650 184
6238 50 1587602 1504455 1282142 1881814 1673668 1994022 1
204029 1853858或者,我们可以使用query( )函数,它也消除了在提及列时指定数据框的需要,并让您编写我们的过滤条
件:income.query(''Y2002>1700000 & Y2003 > 1500000'')处理缺失值我们创建一个名为“cr
ops”的新数据框,并通过导入numpy使用np.nan?创建一个 NaN 值。import numpy as npmydata
= {''Crop'': [''Rice'', ''Wheat'', ''Barley'', ''Maize''], ''Yield'': [1010,
1025.2, 1404.2, 1251.7], ''cost'' : [102, np.nan, 20, 68]}crops = p
d.DataFrame(mydata)crops如果值为 NaN,isnull()返回 True,而notnull()返回 Fal
se。crops.isnull()? #same as is.na in Rcrops.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.i
snull()].Crop #shows the rows with NAs in crops.Cropcrops[crops.c
ost.notnull()].Crop #shows the rows without NAs in crops.Crop要删除任
何行中包含缺失值的所有行,我们使用dropna(how = "any")。默认情况下inplace = False。如果how =
"all"表示如果该行中的所有元素都丢失则删除该行crops.dropna(how = "any").shapecrops.dr
opna(how = "all").shape??如果缺少“产量”或“成本”中的任何一个,要删除 NaN,我们使用子集参数并传递一
个列表:crops.dropna(subset = [''Yield'',"cost"],how = ''any'').shapecrop
s.dropna(subset = [''Yield'',"cost"],how = ''all'').shape用列名中的“UNKNOW
N”子属性替换缺失值。crops[''cost''].fillna(value = "UNKNOWN",inplace = True)
crops处理重复项我们创建了一个包含项目及其各自价格的新数据框。data = pd.DataFrame({"Items" : [
"TV","Washing Machine","Mobile","TV","TV","Washing Machine"], "Pr
ice" : [10000,50000,20000,10000,10000,40000]})data Items Price0
TV 100001 Washing Machine 500002 Mobil
e 200003 TV 100004 TV 100005 Wash
ing Machine 40000duplicated()返回一个逻辑向量,当遇到 duplicated 时返回 True。da
ta.loc[data.duplicated(),:]data.loc[data.duplicated(keep = "first
"),:]默认情况下keep = ''first''即第一次出现被认为是一个唯一值,它的重复被认为是重复的。如果keep = "las
t"最后一次出现被认为是一个唯一值,它的所有重复都被认为是重复的。data.loc[data.duplicated(keep =
"last"),:] #last entries are not there,indices have changed.如果kee
p = "False"然后它认为重复观察的所有出现都是重复的。data.loc[data.duplicated(keep = Fa
lse),:]? #all the duplicates, including unique are shown.要删除重复项,d
rop_duplicates与默认 inplace = False 一起使用,?keep = ''first'' or ''last''
or ''False'' 具有与 duplicated( ) 中的相应含义data.drop_duplicates(keep = "f
irst")data.drop_duplicates(keep = "last")data.drop_duplicates(kee
p = False,inplace = True)? #by default inplace = False创建假人现在我们将考虑
iris 数据集。?iris = pd.read_csv("C:\\Users\\Hp\\Desktop\\work\\Pytho
n\\Basics\\pandas\\iris.csv")iris.head() Sepal.Length Sepal.Widt
h Petal.Length Petal.Width Species0 5.1 3.5
1.4 0.2 setosa1 4.9 3.0
1.4 0.2 setosa2 4.7 3.2
1.3 0.2 setosa3 4.6 3.1
1.5 0.2 setosa4 5.0 3.6
1.4 0.2 setosamap( )函数用于匹配值并在自动创建的新系列中替换它们。iris["seto
sa"] = iris.Species.map({"setosa" : 1,"versicolor":0, "virginica"
: 0})iris.head()要创建假人,使用get_dummies() 。iris.Species.prefix = "Sp
ecies"向创建的新系列添加前缀“Species”。pd.get_dummies(iris.Species,prefix = "
Species")pd.get_dummies(iris.Species,prefix = "Species").iloc[:,0
:1]? #1 is not includedspecies_dummies = pd.get_dummies(iris.Spec
ies,prefix = "Species").iloc[:,0:]使用concat()函数,我们可以连接多个系列或数据帧。axi
s = 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
setosa1 4.9 3.0 1.4 0.2
setosa2 4.7 3.2 1.3 0.2 se
tosa3 4.6 3.1 1.5 0.2 seto
sa4 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 = Truepd.get_dummies(iris,columns = ["Species"],d
rop_first = True).head()排行?要创建所有等级的数据框,我们使用rank()iris.rank()?按特定变
量排名假设我们想按升序排列不同物种的 Sepal.Length:iris[''Rank2''] = iris[''Sepal.Lengt
h''].groupby(iris["Species"]).rank(ascending=1)iris.head()计算累计和使用c
umsum( )函数我们可以获得累积和iris[''cum_sum''] = iris["Sepal.Length"].cumsum(
)iris.head()一个变量的累计和为了找到不同物种萼片长度的累积和,我们使用groupby( )然后使用cumsum( )i
ris["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'',''H
enry'',''Augustus'',''Kenny''],?''Zodiac Signs'': [''Aquarius'',''Libra'',''G
emini'',''Pisces'',''Virgo'']})def name(row): if row["Names"] in ["Joh
n","Henry"]: return "yes" else: return "no"students[''flag''] = stu
dents.apply(name, axis=1)studentspython 中的函数是使用 block 关键字定义的def?,
后跟函数的名称作为块的名称。apply( )函数沿着数据帧的行或列应用函数。Note :如果使用简单的“if else”,我们需要
注意缩进。Python 不涉及循环和 if else 的大括号。输出 Names Zodiac Signs flag0
John Aquarius yes1 Mary Libra no2 Henry
Gemini yes3 Augustus Pisces no4 Kenny Vi
rgo no或者,通过导入 numpy 我们可以使用np.where。第一个参数是要评估的条件,第二个参数是条件为 True
时的值,最后一个参数定义条件评估返回 False 时的值。import numpy as npstudents[''flag''] =
np.where(students[''Names''].isin([''John'',''Henry'']), ''yes'', ''no'')s
tudents多个条件:If Else-if Elsedef mname(row): if row["Names"] == "Jo
hn" and row["Zodiac Signs"] == "Aquarius" : return "yellow" elif
row["Names"] == "Mary" and row["Zodiac Signs"] == "Libra" : retur
n "blue" elif row["Zodiac Signs"] == "Pisces" : return "blue" els
e: return "black"students[''color''] = students.apply(mname, axis=1
)students如果评估为 True,我们创建条件列表及其各自的值,并使用np.select,其中默认值是所有条件为 False
时的值conditions = [ (students[''Names''] == ''John'') & (students[''Zod
iac Signs''] == ''Aquarius''), (students[''Names''] == ''Mary'') & (stud
ents[''Zodiac Signs''] == ''Libra''), (students[''Zodiac Signs''] == ''P
isces'')]choices = [''yellow'', ''blue'', ''purple'']students[''color''] =
np.select(conditions, choices, default=''black'')students Names Zo
diac Signs flag color0 John Aquarius yes yellow1
Mary Libra no blue2 Henry Gemini yes b
lack3 Augustus Pisces no purple4 Kenny Virgo
no black仅选择数字或分类列为了包含数字列,我们使用select_dtypes()?data1 = iris.se
lect_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 cumsum20
5.1 3.5 1.4 0.2 5.1
5.11 4.9 3.0 1.4 0.2
10.0 10.02 4.7 3.2 1.3
0.2 14.7 14.7用于选择分类变量data4 = iris.select_dtypes(include
= [''object''])data4.head(2) Species0 setosa1 setosa拼接我们创建了 2 个包
含学生详细信息的数据框:students = pd.DataFrame({''Names'': [''John'',''Mary'',''Hen
ry'',''Augustus'',''Kenny''],?''Zodiac Signs'': [''Aquarius'',''Libra'',''Gem
ini'',''Pisces'',''Virgo'']})students2 = pd.DataFrame({''Names'': [''John
'',''Mary'',''Henry'',''Augustus'',''Kenny''], ''Marks'' : [50,81,98,25,35]}
)?使用pd.concat( )函数我们可以加入 2 个数据帧:data = pd.concat([students,studen
ts2]) #默认 axis = 0 Marks Names Zodiac Signs0 NaN John
Aquarius1 NaN Mary Libra2 NaN Henry
Gemini3 NaN Augustus Pisces4 NaN Kenny
Virgo0 50.0 John NaN1 81.0 Mary
NaN2 98.0 Henry NaN3 25.0 Augustus Na
N4 35.0 Kenny NaN因此,默认情况下,axis = 0新数据框将按行添加。如果列不存在
,则在其中一个数据框中创建 NaN。为了明智地加入专栏,我们设置axis = 1data = pd.concat([student
s,students2],axis = 1)data Names Zodiac Signs Marks Names0
John Aquarius 50 John1 Mary Libra
81 Mary2 Henry Gemini 98 Henry3 Augustu
s Pisces 25 Augustus4 Kenny Virgo 35
Kenny使用append函数,我们可以按行连接数据帧students.append(students2)? #for row
s或者,我们可以创建两个数据框的字典,并可以使用pd.concat按行连接数据框classes = {''x'': students,
''y'': students2}?result = pd.concat(classes)result?? Marks Na
mes Zodiac Signsx 0 NaN John Aquarius 1 NaN M
ary Libra 2 NaN Henry Gemini 3 NaN Augustus Pisces 4 NaN Kenny Virgoy 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 intersectionsresult Names Zodiac Signs Marks0 John Aquarius 501 Mary Libra 812 Henry Gemini 98?默认情况下how = "inner"因此它只需要两个数据框中的公共元素。如果您想要两个数据框中的所有元素,请设置how = "outer"result = pd.merge(students, students2, on=''Names'',how = "outer")? #it only takes unionsresult Names Zodiac Signs Marks0 John Aquarius 50.01 Mary Libra 81.02 Henry Gemini 98.03 Maria Capricorn NaN4 Augustus NaN 25.05 Kenny NaN 35.0只取交点和左边的所有值 df set how = ''left''result = pd.merge(students, students2, on=''Names'',how = "left")result Names Zodiac Signs Marks0 John Aquarius 50.01 Mary Libra 81.02 Henry Gemini 98.03 Maria Capricorn NaN类似地,how = ''right''仅采用交叉点和右 df 中的所有值。result = pd.merge(students, students2, on=''Names'',how = "right",indicator = True)result Names Zodiac Signs Marks _merge0 John Aquarius 50 both1 Mary Libra 81 both2 Henry Gemini 98 both3 Augustus NaN 25 right_only4 Kenny NaN 35 right_onlyindicator = True创建一个列,用于指示值是否同时存在于数据帧或左数据帧或右数据帧中。?
献花(0)
+1
(本文系云端筑梦师A...原创)