用了三年的 pandas 速查表_第1頁
用了三年的 pandas 速查表_第2頁
用了三年的 pandas 速查表_第3頁
用了三年的 pandas 速查表_第4頁
用了三年的 pandas 速查表_第5頁
已閱讀5頁,還剩12頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領

文檔簡介

1、01環(huán)境搭建 s: s,docs:conda Lio/en/latest/miniconda2 htmlexcel 處理相關包 xlrd / openpyxl / xlsxwriter解析網(wǎng)頁包 requests / Ixml / html51ib / BeautifulSoup4計算包:scipypip install jupyter pandas matplotlib國外網(wǎng)絡慢,可指定國內(nèi)源快速下載安裝一pip install pandas -i Conda多Python版本環(huán)境:創(chuàng)立新環(huán)境,環(huán)境名稱,python版本conda create -n py39 python=329刪除環(huán)境c

2、onda remove -n py39 -allla入、激活環(huán)境conda activate py39退出環(huán)境conda deactivate查看所有虛擬環(huán)境及當前環(huán)境conda info -e02 Jupyter Notebook 快捷鍵啟動 Jupyter Notebook : jupytr notbook快捷鍵及功能: :代碼提示Shifts Enter :執(zhí)行本行并定位到新增的行Shift+Tab(l-3次):查看函數(shù)方法說明D, D :雙擊D刪除本行A / B :向上/下增加一行df .groupby(coll).agg(np.mean) #返回按列coll分組的所有列的均值按列將其

3、他列轉(zhuǎn)行pd.melt(dfid_vars=day, var_name=city, value_name=temperatu re1)交叉表是用于統(tǒng)計分組頻率的特殊透視表 pdcrosstab(df. Nationality,dfHandedness) # groupby后排序,分組agg內(nèi)的元素取固定個數(shù)Idf(df.p_day = 20190101) .groupby(1p_day二 name) .agg(uv:sum).sort_values( p_day1 1 uv1 _, ascending=False False) .groupby(level=0) .head(5) # 每天取

4、5 個頁面.unstack().Plot。_)合并查詢經(jīng)第一個看(max, min, last, size:數(shù)量) dfgroupby(結算類型).first。合并明細并分組統(tǒng)計加總(max, mean: median,prod, sum std/var, 1 nunique1) J nunique,為去重的歹 U 表dfl = df .groupby(by=,設計師工D1).agg(結算金額,:sum)df. groupby (by=df. pf). ip. nunique () # groupby distinct, 分組+去重數(shù) df. groupby (by=df. pf) .ip.

5、value_counts() # groupby 分組+去重的值及數(shù)量 dfgroupby(nameiyLagg(sum, 1 median 1, 1 count1)12數(shù)據(jù)合并合并拼接行將df2中的行添加到dfl的尾部dfl.append(df2)指定列合并成一個新表新列ndf = (df 提名 1.append(df提名 2ignore_index=True).append(df提名 3, ignore_index=True)ndf = pd.DataFrame(ndfcolumns=(姓名)將df2中的列添加到dfl的尾部dfconcat(dfl, df2, axis=l)合并文件的各行

6、_dfl = pd.read_csv(111.csv1 sep=1t1)df2 = pd.read_csv(222.csv1? sep=1t1)excel_list = dfl, df2result = pd.concat(excel_list),):.astype(str)result = pd.concat(excel_list)result.to_excel(333xlsx, index=False)合并指定目錄下所有的 excel (csv) 文件 import globfiles = glob,glob(data/cs/*.xls)dflist = for i in files:df

7、list.append(pd.read_excel(iJ usecols=1 ID1 ,時間,1名稱)df = pd.concat(dflist)合并增加列又寸dfl的歹IJ和df2的歹IJ執(zhí)行SQL形式的join dfl.join(df2Jon=coll how=1 inner1)用key合并兩個表df_all = pd.merge(df_skuJ df_spu, how=leftjleft_on=df_sku1product_id, right_on=df_spup product_id)13時間處理時間序列時間索引df.index = pd.Datetimelndex(dfLindex)

8、時間只保存日期dfdate1 = dftime1.dt.date將指定字段格式化為時間類型dfdate = pd.to_datetime(df時間)轉(zhuǎn)化為北京時間dffime1 = dfftime1. dt .tz_convert(1 Asia/Shanghai1)轉(zhuǎn)為指定格式,可能會失去秒以葡勺精度一dfftime1 = df 1 time1 .dt.strftime(de.index = pd.to_datetime(dc.indexformat=%Y%m%d, errors=ignore1時間,參與運算pd.DateOffset(days=2)當前時間pd.Timestamp.now()

9、pd.to_datetime(1 today1)判融寸間是否當天二()dftime.astype(1datetime64ns1).dt.date = pd.to_datetime(1 today1)定義個天數(shù)一import datetime days = lambda x: datetime.timedelta(days=x) days(2)同工,直接用pd包裝的pd.Timedelta(days=2)unix時間戳pd.to_datetime(ted.film_dateJ unit=,ms1)按月(YMDHminS)采集合訐數(shù)據(jù)df.set_index(date).resample(M1)Q

10、uantity.sum()df. set_index(1 date) .groupby( name1) ext price1 . resample(,M). sum n=按天匯總,index是datetime時間類型df.groupby(by=df.index.date).agg(1uu1:1 count1)按周匯總df.groupby(by=df.index.weekday) uu count()按月進行匯總df.groupby(name,, pd.Grouper(key=1 date, freq=M*)ext price1 sum()按月進行匯總df.groupby(pd.Grouper(

11、key=day1, freq=1 IM1).sum()按照年度,且截止到12月最后一天統(tǒng)計 ext price 的 sum 值df.groupby(name1, pd.Grouper(key=date, freq=A-DEC1) *ext price.sumO按月的平均重新采樣df1 Close.resample(MJ .mean() . /pandas- docs/stable/user_guide/timeseries.html#offset-aliases取時間范圍,并反E作日rng = pd.date_range(start=6/1/2016,end=6/30/20

12、16”,freq=B)重新定時數(shù)據(jù)頻度,按一定補充方法dfasfreq(D, method=1 pad)時區(qū),df .tz_convert( Europe/Berlin )dfetime.tz_localize(tz=Asia/Shanghai1)轉(zhuǎn)北京時尚dfTime1 = dfTime1.dt.tz_localize(,UTC),dttz_convert(Asia/S hanghai1)查看所有時區(qū)from pytz import all_timezonesprint (all_timezones)時長,多仄,兩個時間間隔時間,時差df1 duration = pd.to_datetime

13、(df1 end)- pd.to_datetime(df1 begin1)指定舟間進行比照df.Time.astype(1datetime64ns1) 0 else ; subset=pd.IndexSlice:B 1C1 )最大值最小值加背景色df.style.highlight_max(color=1 lightgreen).highlight_min(color=ttcd 4f 39)df. style, format ( : .2% subset=pd. IndexSlicef: B ) # 顯示百分號指定各列的樣式一format_dict = sum:$0:,date1: :%Y-%

14、m,Pct_of: :.2%1 c: str.upper)# 一次性樣式設置(df.style.format(format_dict) # 多種樣式形式hide_index()裝足列按顏色深度壽歷值大小,cmap旦matplotlib colormap.background_gradient(subset=1sum_num1cmap=1BuGn)表格內(nèi)作橫向bar代表值大小bar(color=#FFA07A, vmin=100_000 subset=1 sum, align=zeroD2Z22表格內(nèi)作橫向bar代表值大小bar(color= lightgreen, vmin=0 subset=

15、1 pct_of_total1 , align =* zero)下降(小于。)為紅色,上升為綠色.bar(color= #ffe4e4, #bbf9ce , vmin=0 vmax=l subset=增長 率,align=zero1)廨樣式表格超個名字.set_caption(12018 Sales Performance1)hide_index()按條件給整行加背景色(樣式)def background_color(row)jif row.pv_num = 10000:return background-color: red 1 * len(row)elif row.pv_num = 100

16、:return 1 background-color: yellow1 * len(row)return ,1 * len(row)使用df,style.apply(background_color, axis=l)16表格中的直方圖,sparkline圖形import sparklinesimport numpy as np def sparkline_str(x):bins=np.histogram(x)0si .join(sparklines.sparklines(bins) return sisparkline_str._name_ = sparkline畫出趨勢圖,保存兩位小數(shù)df,

17、groupby(1 name1)quantity 1 ext price1.agg(mean, sparkline_ str).round(2)sparkline 圖形 s:/hugoworld.wordpress,com/2019/01/26/sparklines-in-jupyter- notebooks-ipython-and-pandas/def sparkline(data, figsize=(4 0)25), *kwargs)2 II II IIcreates a sparklineTurn off the max column width so the images wont b

18、e truncatedpd set_option(1 display.max_colwidth, -1)Turning off jthe jnax olumrwill display all jthe dataif gathering into sets / array we might want to restrict to a few itemspd,set_option(display.max_seq_items, 3)Monkey patch the dataframe so the sparklines are displayedpd.DataFrame._repr_html_ =

19、lambda self: self.to_html(escape=-al se)from matplotlib import pyplot 斗 pit import base64from io import BytesIOdata = list(data)_, ax = pit.subplots(l 1, figsize二figsize, *kwargs) ax.plot(data)ax.fill_between(range(len(data), data, len(data)*min(data), alpha=0.1)ax.set_axis_off() img = BytesIO()pit.

20、savefig(img)plt.close()return 1 .format(base64. b64encode(img.getvalue().decode()#使用df.groupby(1 name)1 quantity, 1 ext price.agg(mean, sparkline df.apply(sparkline axis=l) #僅支持橫向數(shù)據(jù)畫線,可做T轉(zhuǎn)置17可視化kind : strline: line plot (default)bar* : vertical bar plotbarh : horizontal bar plothist: histogrambox: b

21、oxplotkde*: Kernel Density Estimation plotdensity*: same as kdearea*: area plotpie* : pie plot常用方法:df88.plot.bar(y=*rate*figsize=(20J 10) # 圖形大小,單位英寸 df_ldf_lp_day 2019-06-011 .plot.bar(x=1 p_day1, y=1 total_order_num1, order_user figsiz e=(16, 6) # 柱狀圖每條線一個站點,各站點的 home_remain, stack的意思是堆疊,堆積unstack

22、艮不要堆疊”(df(df.p_day = 12019-05-11) & (df.utype =,老客1).groupby(p_day, 1site_id)home_remain.sum().unstack().pl ot.line()折線圖,多條x軸默認為indexdd.plot.line(x=,p_day,y=1uv_all11home_remain1)dd.loc新訪客一一一2.plot.scatter(x=,order_user1y=1paid_order_user) # 散人M圖dd.plot.bar(color=blue) # 柱狀圖,barh 為橫向柱狀圖sns. heatmap(

23、dd. corr() # 相關性可視化刻度從0開始,指定范圍ylim=(0,100), x軸相同s plot ,line(ylim=0)折線顏色 s://examples/color/named_colors.html樣式(.J-J:)一折線標記 s://api/markers_api.htmlgrid=True 顯示亥U度 etc 二 s /matplotlibLorg/api/_as_gen/matplotlibLpyplot Lplot.h tmlsplotline(color=green, linestyle=-, marker=

24、o)兩個圖繪在一起df 數(shù)量 H .plot.kde(), dfp 數(shù)量,.plot . hist()對表中的數(shù)據(jù)按顏色可視化import seaborn snscm = sns.light_palette(green11 s_cmap=Tue) df.style.background_gradient(cmap=cmJ axis=l)將數(shù)據(jù)轉(zhuǎn)化為二維數(shù)組i for i in zip( i.strftime(%d) for i in s.index.to_list(), s.to_list()和 plot 用法一樣 import hvplot.pandas打印Sqlite建表語句一print(

25、pdio.sql.get_schema(fdf, table_name)18 Jupyter notebooks 問題jupyter notebooks pit 圖表配置 import matplotlib.pyplot as pit pit. rc Pa rams figure, figsize = (15.0, 8.0) # 固定顯示大小 pit. rcParams *font .family = 1 sans-serif # 顯示中文問題 pit.rcParamsf font.sans-serif = 1 SimHei1 # 顯示中文問題輸出單行全部變量from IPython.core

26、.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = alljupyter notebooks 頁面自適應寬度from IPython.core.display import display, HTML display(HTML(n.container width:100% !important; 1)_Sjstyle#notebook_panel backgroundj_ffffffjupyter notebooks嵌入頁面內(nèi)容from 工Python.display impor

27、t IFrameIFrame(* s:arxiv. org/pdf/1406 2661 pdf, width=800, height=450:Markdown 一個cell不支持多張粘貼圖片一個文件打印翻開只顯示一張圖片問題解決/site-packages/notebook/static/notebook/js/main.min.js var key 處 # 33502、 33504 行key = utils.uuid().slice(2 6)+encodeURIandParens();key = utils.uuid(),slice(2,6)+Object.keys(tha

28、t.attachments).length;# s:/github /ihnorton/notebook/commit/55687c2dc08817da58797 7cb6fl9f8cc0103babl多行輸出from IPeractiveshell import InteractiveShell InteractiveShell. ast_node_interactivity = 1 all1 #默認為last執(zhí)行shell命令:!命令語句在線可視化工具 s:/plot ,ly/create19 Slideshow 幻燈片安裝 RISE 庫:pip install

29、 RISEAlt+r播放/退出播放,逗號隱藏左側兩個大操作按鈕,總覽ppt, /黑屏Slide :主頁面,通過按左右方向鍵進行切換。Sub-Slide :副頁面,通過按上下方向鍵進行切換。全屏Fragment : 一開始是隱藏的,按空格鍵或方向鍵后顯示,實現(xiàn)動態(tài)效果。在一個頁面Skip :在幻燈片中不顯示的單元。Notes :作為演講者的備忘筆記,也不在幻燈片中顯示。M / Y : Markdown / 代碼模式03導入庫包import pandas as pd # 最新為 1.4.1 版本(2022-02-12)import numpy as npimport matplotlib.pypl

30、ot as pitimport seaborn as sns%matplotlib inline04導入數(shù)據(jù)從csv文件導入數(shù)據(jù)pd.read_csv(1 file.csv, name=列名1,列名 21)從限&隔符的文本文件導入數(shù)據(jù)pd , read_table(filenameJ header=0)Excel導入,指定sheet和表頭pd.read_excel(file.xlsx1sheet_name=1 表 1, header=0)從SQ【表/庫導入數(shù)據(jù)一pdread_sql(queryJ connection_object)從js6n格式的字符串導入數(shù)據(jù)一pd read_json(js

31、on_string)解析URL、字符串金者HTML文件,抽取其中的tables表格pd read_html(url)從你的粘貼板獲取內(nèi)容,并傳給read_table()pd read_clipboard()從字始寸象導入數(shù)據(jù),Key是列名,Value是數(shù)據(jù)pd.DataFrame(diet)導入字符串from io import StringlOpd , read_csv(String1O(web_data.text)05導出輸出數(shù)據(jù)導出數(shù)據(jù)到csv文件 df.to_csv(filename.csvJ導礴據(jù)到Excel友伴dfto_excel(filenamexlsxj index=True)

32、導由藪據(jù)到SQL表df,to_sql(table_nameJ connection_object)以上on格式導出數(shù)據(jù)到文本文件 df.to json(filename)其面df .to_html() # 顯示 HTML 代碼df .to_markdown() # 顯示 markdown 代石馬df.to_string() #顯示格式化字符df.to_latex(index=False) # LaTeX tabu1ar, 1ongtab1e df,to_dict(split) # 字典, 格式 list/series/records/index df .to_clipboard(sep=, i

33、ndex=False) # 存入系統(tǒng)剪貼板將兩個表格輸出到一個excel文件里面,導出到多個sheetwriter=pd.ExcelWriter(new.xlsx1)df_l.to_excel( writer sheet_name=,第一個 index=二a Ise) df_2.to_excel(writerJsheet_name=第二個,index=False) writer.save() #必須運行writer.save(),不然不能輸出到本地寫法2with pd.ExcelWriter(ew.xlsx1) as writer:dfl.to_excel(writer, sheet_name

34、=第一個1)df2.to_excel(writer, sheet_name=1 第二個)用xlsxw;iter導出支持合并單贏、顏色、圖表等定制功能 s:/xlsxwriter. readthedocs . io/working_with_pandas . html06創(chuàng)立測試對象創(chuàng)立20行5列的隨機數(shù)組成的DataFrame 對象(20 5)從可迭代對象my_list創(chuàng)立二Series對象 pd.Series(my_list)增加一個日斯索引df.index = pd.date_range(11900/1/30periods=df.shape0)創(chuàng)立隨機數(shù)據(jù)集 一df = pd.util.t

35、esting.makeDataFrame()創(chuàng)立隨機日期索引數(shù)據(jù)集df = pd.util.testingmakePeriodFrame()df = pd.util.testing.makeTimeDataFrame()創(chuàng)立隨機混合類型數(shù)據(jù)集df r pdutil.testing.makeMixedDataFrame()07查看、檢查、統(tǒng)計、屬性df .head(n) # 查看 DataFrame 對象的前n行df.tail(n) #查看DataFrame對象的最后n行df.sample(n) #查看n個樣本,隨機df.shape #查看行數(shù)和列數(shù)() #查看索引、數(shù)據(jù)類型和內(nèi)存

36、信息df.describe。# 查看數(shù)值型列的匯總統(tǒng)計df .dtypes #查看各字段類型df.axes #顯示數(shù)據(jù)行和列名df.mean() #返回所TT列的均值df.mean(l) # 返回所有行的均值,下同df.corr() #返回列與列之間的相關系數(shù)df.count() #返回每一列中的非空值的個數(shù)df.max() #返回每一列的最大值df.min() #返回每二列的最小值df.median。#返回每一列的中位數(shù)df.std() # 返回每一列的標準差df.var() # 方差s.mode() # 眾數(shù)d() # 連乘s.cumprod() #累積連乘,累乘df.cumsu

37、m(axis=0) # 累積連加)累加s.nunique() #去重數(shù)量,不同值的量df idxmax() #的值的df.idxmin() # 最小df.columns # 顯示所有列名df.team.unique() #顯示列中的不重復值查看Series對象的唯一值和計數(shù),計數(shù)占比:normalize=True s.value_counts(dropna=False)查看 DataFrame 對象中每一列的唯一值和計數(shù)df.apply(pd.Series.value_counts)df. duplicated() # 重復行df .drop_duplicates() # 刪除重復行set_o

38、ption. reset_option. describe_option 設置顯示要求 pd.get_option()飯置行列最大虛宗數(shù)量,None為不限制pd.options.display.max_rows = Nonepd.options.display.max_columns = Non。dfcoLargmin() # 最大殖最小值 argmax() 所在位置的自動索引df colidxmin() # 最大值最小值 idxmax() 所在位置的定義索引累計統(tǒng)計ds.cumsum() #前邊所有值之和ds.cumprod() # 前邊所有值之積ds.cummax() #前邊所有值的最大值

39、ds cummin() # 前邊所有值的最小值#窗口計算C袞動計算)dsrolling(x).sum() #依次計算相鄰x個元素的和ds. rolling(x).mean() #依次計算相鄰 x 個元素的算術平均ds.rolling(x) .var() #依次計算相鄰 x 個元素的方差ds.rolling(x) .std() #依次計算相鄰x個元素的標準差ds.rolling(x) .min() #依次計算相鄰 x 個元素的最小值ds.rolling(x) .max() #依次計算相鄰x個元素的最大值08數(shù)據(jù)清理df.columns =# 重命名歹U名df. columns = df. col

40、umns. str. replace (1 ) # 列名空格換卜劃線df.locdf.AAA = 5, BBB,,CCC = 555 #dfpF = df.site_id.map(2: 小程序7:M站) #將枚舉換成名稱 pd.isnull() #檢查DataFrame對象中的空值,并返回一不Boolean數(shù)組 pd.notnull() #檢查DataFrame對象中的非空值,并返回一個Boolean數(shù)組 df .drop( name j axis=l) # 刪除列 dfdrop(0, 10, axis=0) # 刪除行del dff name1 # 刪除列df.dropna() #刪除所有包

41、含空值的行df.dropna(axis=l) #刪除所有包含空值的列df .dropna(axis=lJthresh=n) #刪除所有小于n個非空值的行df .fillna(x) #用x替換DataFrame對象中所有的空值什.011恒311=卬0丫,:,未知,) #指定列的空值替換為指定內(nèi)容s.astype(float) #將Series中的數(shù)據(jù)類型更改為float類型 df. index. astype( datetime64ns1) # 轉(zhuǎn)化為時間格式 s.replace(l, one1) #用,one代替所有等于1的值s.replace(l, 3Hone,three,) # 用one代

42、替 1, 用 three,代替 3df.rename(columns=lambda x: x + 1) # 批量更改列名df .rename(columns= ,old_name, : 1 new_name ) # 選擇性更改列名df. set_index( column_one) # 更改索引列df.rename(index=lambda x: x + 1) # 批量重命名索引#重新命名表頭名稱df.columns =IHA,當前待打款金額;認證姓名什是否設置提現(xiàn)賬號=df狀態(tài)#復制一列df.loc:, :-1 # 列順序反轉(zhuǎn)一df.loc:-l #行順序反轉(zhuǎn),下方為重新定義索引df.loc

43、:-11,reset_index(drop=True)09 數(shù)據(jù)處理:Filter% Sort#保存小數(shù)位,四舍六入五成雙df. round(2) # 全部df.round(,A, : 1,2) # 指定列df1 Name1 = df.Name # 取歹1名的兩個方法dfdf.index = 1 Dude1 # 按索引查詢要用.indexdfdfcol 0.5 #選擇col列的值大于0.5的行#多條件查詢dftCdffteam1 = A) &(dfQlJ 80) &(老客老訪客)篩選為空的內(nèi)容dfdf.order.isnull()類似 SQL where indfdf.team.isin(,A

44、,/B,)df(df.team=,B,) & (df.QI = 17)df(dfteam = A) | ( dffQl1 80) # 非,或df df. Name. str. contains () # 包含字符df .sort_values(coll) #/照列coll力評數(shù)墀,默認開后排列df.coll.sort_values() # 同上,- sdf.sort_values(col2J ascending=False) # 按照列 coll 降序排列數(shù)據(jù)先按歹coll升序排列,至按CO12降舊步I數(shù)據(jù)df.sort_values(coll,col2, ascending=True,二aI

45、se)df2 = pd.get_dummies(dfprefix=t_)#將枚舉的那些列帶枚舉轉(zhuǎn)到列上 s.set_index().plot()多痢I處理ddset_index(1utype, site_id1, p_day, inplace=True)dd. sort_index(inplace=True) # 按索引排序dd.loc新訪客2, , 2019-06-22, .plot.barh() # loc 中按序指定裁 I 內(nèi)容前100行,不能指定行,如:df 10。df:100只取指定行dfl = df.loc0:,設計師工D姓名將ages平分成5個區(qū)間并指定 labelsages =

46、 np.array(1,5,10,40,36,12,58,62,77,89,100,18,20,25,30,32) pd.cut(ages, 0,5,20,30,50,100labels=u“嬰兒二u”青年Lu“中年u“壯年u“老年”)daily_index.difference(df_work_day.index) # 取出J;別格如匕 # 索川的名稱 strdf.columns .tolist()df.values.tolist()df ,總人口 .values.tolist()data.apply(np.mean) # 對 DataFrame 中的每一列應用函數(shù)

47、 np.meandata.apply(np.maxaxis=l) # 對 DataFrame 中的每一行應用函數(shù) np.maxdf.insert(l., 1three, 12, allow_duplicates=False) # 插入列(位置、列 京面)一df .pop( class1) # 刪除列增加一行df.append(pd.DataFrame(one:2, two:3, three : 4.4, index=*f*), sort=True)指定新列iris.assign(sepal_ratio=irisSepalWidth / irisSepalLength).h ead()df.as

48、sign(rate=lambda df: df.orders/df.uv)shift函數(shù)是對數(shù)據(jù)進行平移動的操作肝增幅=df國內(nèi)生產(chǎn)總值-國內(nèi)生產(chǎn)總值df.tshift(l) #時間移動,按周期和上相同,diff函數(shù)是用來將數(shù)據(jù)進行移動之后與原數(shù)據(jù)異數(shù)據(jù),等于dfshift()-肝df增幅=肝國內(nèi)生產(chǎn)總值留存數(shù)據(jù),因為最大一般為數(shù)據(jù)池df.apply(lambda x: x/xmax(), axis=l)best 列中值為列名的值寫到 name 行上df2yalue* = dfaookup(df ,name, , dffbestJJswhere(s 1, 10) #滿足條件下數(shù)據(jù)替換(10,空

49、為NaN)s.mask(s 0) #留下滿足條件的,其他的默認為NaN所有值加1 (加減乘除等)df + 1 / df.add(l)#管道方法, def gb(df, result result return#管道方法, def gb(df, result result return#鏈式調(diào)用函數(shù),f(df)=df.pipe(f) by):=df.copy()=result.groupby(by).sum() resultdfpipe(gb, by=,team,)窗口計算Is,為兩秒df.rolling(2).sum()在窗口結果基礎上的窗口計算df.expanding(2).sum()超出(

50、大于、小于)的值替換成對應值 df.clip(-4 6)AB兩列想加增加C列dffC1 = df.eval(A+B)和上相同效果df .eval( *C = A + B inplace=True)數(shù)列的變化百分比s pct_change(periods=2)分任及,可實現(xiàn)時間的中間點 df.quantile(25)排名 average minmax?first, dense, 默認 average s.rank()數(shù)據(jù)爆炸,將本列的類列表數(shù)據(jù)和其他列的數(shù)據(jù)展開鋪開 df.explode(A)枚舉更新status = 0:沫執(zhí)行工:執(zhí)行中21執(zhí)行完畢3廠執(zhí)行異常dftaskstatus1 = dftaskstatus.apply(status.get) df.assign(金額=0) # 新增字段dfloc(bar two), A # 多索引查詢df.query(*i0 = HbH & il = Hbn,) # 多索引查詢方法 2取多索引中指定級別的所有不重復值df.index.get_level_values(2).uni

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論