亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用自動生成的類別和箱從 Pandas cut() 命令創建個性化的桶列?

如何使用自動生成的類別和箱從 Pandas cut() 命令創建個性化的桶列?

嚕嚕噠 2022-06-02 10:20:01
我有一個包含多列的 Pandas DataFrame。其中之一是year. 在此列中,我想創建一個具有分類值的新列(我猜 therm 是存儲桶),并自動生成存儲桶。它應該導致類似的結果:year_gr         year    other_colsA (1909 - 1917) 1911    abcB (1921 - 1930) 1923    defC (1932 - 1941) 1935    ghi我設法通過以下方式創建接近它的東西:year_gr = pd.cut(df.year, 10, labels=[   'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'])df['year_gr'] = year_grdf.head()year_gr year    other_colsA       1911    abcB       1923    defC       1935    ghi但是如何將自動生成的憤怒連接pd.cut到我的year_gr變量?我看到我們可以retbins=True在cut命令中添加參數來提取垃圾箱,但我沒有設法利用它......謝謝!
查看完整描述

1 回答

?
青春有我

TA貢獻1784條經驗 獲得超8個贊

pd.cut 產生一個由區間對象填充的類別對象。我們使用它們的 .left 和 .right 屬性來創建指定的字符串。


    import numpy as np, pandas as pd

    import string


    # test data:

    df=pd.DataFrame({"year":[1911,1923,1935,1911],"other_cols":["abc","def","ghi","jkl"]})

  Out:

           year other_cols

    0  1911        abc

    1  1923        def

    2  1935        ghi

    3  1911        jkl


    #create the intervals:

    cats=pd.cut(df.year,10)


    Out: cats.dtypes.categories

    IntervalIndex([(1910.976, 1913.4], (1913.4, 1915.8], (1915.8, 1918.2],...


    # char generator:

    gchar=(ch for ch in string.ascii_uppercase)

    dlbls= { iv:next(gchar) for iv in cats.dtypes.categories } #EDIT1

    # get the intervals and convert them to the specified strings:

    df["year_gr"]=[ f"{dlbls[iv]} ({int(np.round(iv.left))} - {int(np.round(iv.right))})" for iv in cats ] #EDIT1

   Out:

          year other_cols          year_gr

    0  1911        abc  A (1911 - 1913)

    1  1923        def  B (1921 - 1923)

    2  1935        ghi  C (1933 - 1935)

    3  1911        jkl  A (1911 - 1913)


    # align the columns:

    df= df.reindex(["year_gr","year","other_cols"], axis=1)

   Out:

               year_gr  year other_cols

    0  A (1911 - 1913)  1911        abc

    1  B (1921 - 1923)  1923        def

    2  C (1933 - 1935)  1935        ghi

    3  A (1911 - 1913)  1911        jkl


查看完整回答
反對 回復 2022-06-02
  • 1 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號