当前位置: 首页 > 科技观察

分享30个超好用的Pandas实用技巧

时间:2023-03-13 13:45:23 科技观察

读取数据read_csv()用于读取csv格式的数据集,当然我们在里面还有很多未解之谜。pd.read_csv("data.csv")只读取数据集中的几列。我们只想读取数据集中的几列,所以我们可以调用usecols参数。代码如下:df=pd.read_csv("house_price.csv",usecols=["Id","SalePrice"])df.head()输出时间类型数据分析主要用到了parse_dates参数,代码如下如下:df=pd.read_csv("Tesla.csv",parse_dates=["Date"])df.head()输出设置数据类型。主要调用是dtype参数。同时,合适的数据类型可以为数据集节省大量的内存空间。代码如下:df=pd.read_csv("data.csv",dtype={"house_type":"category"})参数index_col用于设置索引,代码如下:df=pd.read_csv("Tesla.csv",index_col="Date")df.head()输出只读取部分使用nrows参数的read,代码如下:df=pd.read_csv("Tesla.csv",nrows=100)df.shapeoutput(100,7)跳过一些行如果数据集中有一些我们不想包含的内容,可以直接跳过,skiprows参数,代码如下:pd.shapeoutput(100,7)read_csv("data.csv",skiprows=[1,5])#跳过第一行和第五行pd.read_csv("data.csv",skiprows=100)#跳过前100行pd.read_csv("data.csv",skiprows=lambdax:x>0andnp.random.rand()>0.1)#提取10%的数据,遇到空值怎么办?如果遇到空值,我们可以将空值替换为其他值,代码如下:df=pd.read_csv("data.csv",na_values=["?"])布尔值呢?对于布尔值,我们也可以设置其他值来代替,代码如下:df=pd.read_csv("data.csv",true_values=["yes"],false_values=["no"])readdatafrommultiplecsvfiles也可以从多个csv文件中读取数据,通过glob模块,代码如下:importglobimportosfiles=glob.glob("file_*.csv")result=pd.concat([pd.read_csv(file)forfileinfiles],ignore_index=True)iffromReaddatafromPDFfiles.我们的表单数据存在于pdf文件中。我们需要从pdf文件中读取数据。代码如下:#安装tabula-py模块#%pipinstalltabula-pyfromtabulaimportread_pdfdf=read_pdf('test.pdf',pages='all')探索性数据分析的三行代码直接生成一个数据通过调用pandas_profilling模块分析报告,代码如下:#安装pandas-profilling模块#%pipinstallpandas-profilingimportpandas_profilingdf=pd.read_csv("data.csv")profile=df.profile_report(title="PandasProfilingreport")profile.to_file(output_file="output.html")基于数据类型,pandas可以表示的数据有很多种,可以根据数据类型过滤数据。我们希望过滤后的数据包含或者不包含我们想要的数据类型的数据。代码如下:#过滤数据df.select_dtypes(include="number")df.select_dtypes(include=["category","datetime"])#排除数据df.select_dtypes(exclude="object")推断数据类型主要调用了infer_objects()方法,代码如下:df.infer_objects().dtypes手动数据类型我们手动进行数据类的转换类型转换,如果不能转换,errors='coerce'将其转换为NaN,代码如下:#对整个数据集有效df=df.apply(pd.to_numeric,errors="coerce")#用零填充空值pd.to_numeric(df.numeric_column,errors="coerce").fillna(0)使用astype方法一次性完成数据类型转换,代码如下:df=df.astype({"date":"datetime64[ns]","price":"int","is_weekend":"bool","status":"category",})columnrenamerename()列重命名的方法,代码如下:df=df.rename({"PRICE":"price","Date(mm/dd/yyyy)":"date","STATUS":"status"},axis=1)添加一个前缀或一个后缀的add_prefix()方法和add_suffix()方法,代码如下:df.add_prefix("pre_")df.add_suffix("_suf")新建一个列并调用assign方法,当然有还有其他方法可以试试,代码如下:#摄氏度和华氏度之间的数制转换df.assign(temp_f=lambdax:x.temp_c*9/5+32)同样在指定位置插入一个新列使用insert方法,代码如下:random_col=np.random.randint(10,size=len(df))df.insert(3,'random_col',random_col)#在第三列插入if-else逻辑判断df["price_high_low"]=np.where(df["price"]>5,"high","low")移除部分列并调用drop()方法,代码如下:df.drop('col1',axis=1,inplace=True)df=df.drop(['col1','col2'],轴=1)df.drop(df.columns[0],inplace=True)stringoperationcolumnnameoperation如果我们想对columnname做一些改变,代码如下:#Forcolumnnamestringoperationdf.columns=df.columns.str.lower()df.columns=df.columns.str.replace('','_')Contains()方法##包含一些字符串df['name'].str.contains("John")##正则表达式可以放在df['phone_num'].str.contains('...-...-....',regex=True)#regexfindall()方法##正则表达式模式='([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\\.([A-Z]{1,9})'df['电子邮件']。str.findall(pattern,flags=re.IGNORECASE)检查缺失值的空值比例如果我们要检查数据集中空值的比例,代码如下:defmissing_vals(df):"""空值百分比"""missing=[(df.columns[idx],perc)foridx,percinenumerate(df.isna().mean()*100)ifperc>0]iflen(missing)==0:return"没有空数据"#sortmissing.sort(key=lambdax:x[1],reverse=True)print(f"Theretheretotal{len(missing)}Avariablehasanullvalue\n")fortupinmissing:print(str.ljust(f"{tup[0]:<20}=>{round(tup[1],3)}%",1))输出中一共有19个变量为空值PoolQC=>99.521%MiscFeature=>96.301%Alley=>93.767%Fence=>80.753%FireplaceQu=>47.26%LotFrontage=>17.74%GarageType=>5.548%GarageYrBlt=>5.548%GarageFinish=>5.548%GarageQual=>5.548%GarageF0t0mB2s=>Bs>2.603%BsmtQual=>2.534%BsmtCond=>2.534%BsmtFinType1=>2.534%MasVnrType=>0.548%MasVnrArea=>0.548%Electrical=>0.068%我们可以选择去除空值,或者使用平均值或者其他值填充,代码如下:#去掉空值df.dropna(axis=0)df.dropna(axis=1)#替换成其他值填充df.fillna(0)df。fillna(method="ffill")df.fillna(method='bfill')#替换为其他值df.replace(-999,np.nan)df.replace("?",np.nan)#猜测它的空值应该是什么其他值ts.interpolate()#时间序列df.interpolate()#填充所有连续值forwarddf.interpolate(limit=1)#填充一个连续值forwarddf.interpolate(limit=1,limit_direction="backward")df.interpolate(limit_direction="both")日期格式的数据处理获取指定时间的数据#从今天开始算,然后是N天或者N周或者N小时的日期。today()+datetime.timedelta(hours=30)date.today()+datetime.timedelta(days=30)date.today()+datetime.timedelta(weeks=30)#去年date.today()-日期时间.timedelta(days=365)按日期时间获取数据df[(df["Date"]>"2015-10-01")&(df["Date"]<"2018-01-05")]获取databyspecifiedadate#筛选出某一天的数据df[df["Date"].dt.strftime("%Y-%m-%d")=="2022-03-05"]#Filterout某月的数据df[df["Date"].dt.strftime("%m")=="12"]#过滤出每一年的数据df[df["Date"].dt.strftime("%Y")=="2020"]将数据集格式化保留指定位数对于一些浮点型数据,我们希望保留小数点后两三位,代码如下:format_dict={"打开":"${:.2f}","关闭":"${:.2f}","音量":"{:,}",}df.style.format(format_dict)输出高亮数据对于一些指定的数据,我们希望高亮显示,代码如下:(["Open"],color="red").background_gradient(subset="Close",cmap="Greens").bar('音量e',color='lightblue',align='zero').set_caption('2017年特斯拉股票价格'))output