python中pandas常用命令詳解

    pandas 是基于NumPy 得一種工具,該工具是為了解決數據分析任務而創建得。Pandas 納入了大量庫和一些標準得數據模型,提供了高效地操作大型數據集所需得工具。pandas提供了大量能使我們快速便捷地處理數據得函數和方法。你很快就會發現,它是使Python成為強大而高效得數據分析環境得重要因素之一。

    1、pandas

    pandas 是一個多功能且功能強大得數據科學庫。 

    2、讀取數據

    pd.read_csv("data.csv")

    3、讀取指定列

    pd.read_csv("data.csv", usecols=["date", "price"])

    4、讀取并解析日期

    pd.read_csv("data.csv", parse_dates=["date"])

    5、讀取時指定數據類型

            在讀取時設置類別數據類型可以節省內存。

    pd.read_csv("data.csv", dtype={"house_type": "category"})

    6、讀取時設置索引

    pd.read_csv("data.csv", index_col="date")

    7、設置讀取得行數

    pd.read_csv("data.csv", nrows=100)

    8、讀取時跳過行數

    pd.read_csv("data.csv", skiprows=[1, 5])  # skips line 1 and 5pd.read_csv("data.csv", skiprows=100)  # skips the first 100 linespd.read_csv("data.csv", skiprows=lambda x: x > 0 and np.random.rand() > 0.1) # skip 90% of the rows

    9、指定NA值

    pd.read_csv("data.csv", na_values=["?"])

    10、設置布爾值

    pd.read_csv("data.csv", true_values=["yes"], false_values=["no"])

    11、一次讀取多個文件后合并

    import globimport osfiles = glob.glob("file_*.csv")result = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)

    12、復制數據

    df = pd.read_clipboard() 

    13、從 PDF 文件中讀取表格

    from tabula import read_pdf# Read pdf into list of DataFramedf = read_pdf('test.pdf', pages='all')

    14、快速可視化數據集

    import pandas_profilingdf = pd.read_csv("data.csv")profile = df.profile_report(title="Pandas Profiling Report")profile.to_file(output_file="output.html")

    15、按dtype過濾列

    # 選擇df.select_dtypes(include="number")df.select_dtypes(include=["category", "datetime"]) # 排除df.select_dtypes(exclude="object")

    16、推斷數據類型

    df.infer_objects().dtypes

    17、向下轉換數值類型

    pd.to_numeric(df.numeric_col, downcast="integer") # smallest signed int dtypepd.to_numeric(df.numeric_col, downcast="float")  # smallest float dtype

    18、防止錯誤值并填充

    # apply to whole data framedf = df.apply(pd.to_numeric, errors="coerce")# apply to specific columnspd.to_numeric(df.numeric_column, errors="coerce")# filling NA values with zeropd.to_numeric(df.numeric_column, errors="coerce").fillna(0)

    19、按列數據類型轉換

    df = df.astype(    {        "date": "datetime64[ns]",        "price": "int",        "is_weekend": "bool",        "status": "category",    })

    20、重命名列

    df = df.rename({"PRICE": "price", "Date (mm/dd/yyyy)": "date"}, axis=1)

    21、添加后綴和前綴

    df.add_prefix("pre_")df.add_suffix("_suf")

    22、從原列創建新列

    # create new column of Fahrenheit values from Celciusdf.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32)

    23、在特定位置插入列

    random_col = np.random.randint(10, size=len(df))df.insert(3, 'random_col', random_col) # inserts at third column

    24、三元表達式

    df["logic"] = np.where(df["price"] > 5, "high", "low")

    25、刪除列

    df.drop('col1', axis=1, inplace=True)df = df.drop(['col1','col2'], axis=1)s = df.pop('col')del df['col']df.drop(df.columns[0], inplace=True)

    26、修改列名

    df.columns = df.columns.str.lower()df.columns = df.columns.str.replace(' ', '_')

    27、判斷包含

    df['name'].str.contains("John")df['phone_num'].str.contains('...-...-....', regex=True)  # regexdf['email'].str.contains('gmail')

    28、根據正則查找

    pattern = '([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})'df['email'].str.findall(pattern, flags=re.IGNORECASE)

    29、檢查缺失值并打印缺失百分比

    def missing_vals(df):    """prints out columns with perc of missing values"""    missing = [        (df.columns[idx], perc)        for idx, perc in enumerate(df.isna().mean() * 100)        if perc > 0    ]     if len(missing) == 0:        return "no missing values"        # sort desc by perc    missing.sort(key=lambda x: x[1], reverse=True)     print(f"There are a total of {len(missing)} variables with missing valuesn")     for tup in missing:        print(str.ljust(f"{tup[0]:<20} => {round(tup[1], 3)}%", 1))missing_vals(df)

    30、處理缺失值

    # drop df.dropna(axis=0)df.dropna(axis=1)# imputedf.fillna(0)df.fillna(method="ffill")df.fillna(method='bfill')# replacedf.replace( -999, np.nan)df.replace("?", np.nan)# interpolatets.interpolate() # time seriesdf.interpolate() # fill all consecutive values forwarddf.interpolate(limit=1) # fill one consecutive value forwarddf.interpolate(limit=1, limit_direction="backward")df.interpolate(limit_direction="both")

    31、從今天/之前獲取 X 小時/天/周

    # from todaydate.today() + datetime.timedelta(hours=30)date.today() + datetime.timedelta(days=30)date.today() + datetime.timedelta(weeks=30) # agodate.today() - datetime.timedelta(days=365)

    32、過濾兩個日期

    df[(df["Date"] > "2015-01-01") & (df["Date"] < "2017-01-01")]

    33、按日/月/年過濾

    df[(df["Date"] > "2015-01-01") & (df["Date"] < "2017-01-01")]

    34、格式化數據格式

    format_dict = {    "Date": "{:%d/%m/%y}",    "Open": "${:.2f}",    "Close": "${:.2f}",    "Volume": "{:,}",} df.style.format(format_dict)

    35、設置數據顏色

    (    df.style.format(format_dict)    .hide_index()    .highlight_min(["Open"], color="red")    .highlight_max(["Open"], color="green")    .background_gradient(subset="Close", cmap="Greens")    .bar('Volume', color='lightblue', align='zero')    .set_caption('Tesla Stock Prices in 2017'))

    36、獲取一列中最大最小項得id

    df['col'].idxmin()df['col'].idxmax()

    37、對數據列應用函數

    df.applymap(lambda x: np.log(x))

    38、隨機打亂數據

    df.sample(frac=1, random_state=7).reset_index(drop=True)

    39、時間序列得百分比變化

    df['col_name'].pct_change()

    40、分配等級

    df['rank'] = df['column_to_rank'].rank()

    41、檢查內存占用

    df.memory_usage().sum() / (1024**2) #converting to MB

    42、將列得值分解為多行

    df.explode("col_name").reset_index(drop=True)

    43、將數量較小得類別轉換為“其他”

    subclass = df.MSSubClasssubclass.value_counts()top_five = subclass.value_counts().nlargest(5).indexmssubclass_new = subclass.where(subclass.isin(top_five), other="Other")mssubclass_new.value_counts()

    到此這篇關于python中pandas常用命令得內容就介紹到這了,更多相關python pandas常用命令內容請搜索之家以前得內容或繼續瀏覽下面得相關內容希望大家以后多多支持之家!

    聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。
    發表評論
    更多 網友評論1 條評論)
    暫無評論

    返回頂部

    主站蜘蛛池模板: 亚洲制服中文字幕第一区| 国产精品视频第一区二区三区| 无码国产精品久久一区免费| 三上悠亚一区二区观看| 日本福利一区二区| 久久91精品国产一区二区| 亚洲无线码一区二区三区| 日韩一区二区视频| 色久综合网精品一区二区| 综合久久一区二区三区 | 精品一区二区三区东京热| 日韩有码一区二区| 日本v片免费一区二区三区| AV天堂午夜精品一区二区三区| 亚洲国产美女福利直播秀一区二区| 鲁丝片一区二区三区免费| 久久91精品国产一区二区| 精品一区二区在线观看| 少妇激情av一区二区| 亚洲福利一区二区三区| 无码一区二区三区老色鬼| 无码日韩精品一区二区免费暖暖| 精品一区二区三区免费| 无码精品人妻一区二区三区人妻斩| 一区二区三区视频在线观看| 中文字幕一区二区三区5566| 91视频一区二区三区| 无码精品不卡一区二区三区| 国产色欲AV一区二区三区| 精品一区二区三区在线视频观看 | 亚洲熟妇AV一区二区三区宅男| 亚洲av成人一区二区三区| 成人精品一区二区户外勾搭野战| 中文乱码人妻系列一区二区| 日本精品一区二区在线播放| 一区二区三区四区在线视频| 久久精品一区二区三区不卡| 精品一区二区三区自拍图片区| 天堂va在线高清一区| 免费一区二区无码视频在线播放 | 亚洲熟妇AV一区二区三区宅男|