代码之家  ›  专栏  ›  技术社区  ›  adventurous_chip_55

如何引爆柱子

  •  -1
  • adventurous_chip_55  · 技术社区  · 4 月前

    无法使用熊猫爆炸df。

    我想在Jupyter Notebook的数据帧中“分解”一个带有命名子列的命名列。

    以下是数据帧:

       State or territory  Census population[8][9][a]               
       State or territory         July 1, 2024 (est.)  April 1, 2020
    0          California                  39431263.0       39538223
    1               Texas                  31290831.0       29145505
    2             Florida                  23372215.0       21538187
    3            New York                  19867248.0       20201249
    4        Pennsylvania                  13078751.0       13002700
    

    我想爆炸人口普查人口,然后删除2020年4月1日,留下“州或地区”和“2024年7月1日(估计)”

    import pandas as pd
    
    tables1 = pd.read_html("https://en.wikipedia.org/wiki/Fortune_500")
    tables2 = pd.read_html(
        "https://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_population")
    
    df1 = tables[1]
    df2 = tables2[0]
    
    df1copy = df1.drop(["Rank"], axis=1)
    df2copy = df2.drop(
        ["Change, 2010–2020[9][a]",
         "House seats[b]",
         "Pop.  per elec. vote (2020)[c]",
         "Pop. per seat (2020)[a]",
         "% US (2020)",
         "% EC (2020)"],
        axis=1)
    print(df1copy.head())
    print(df2copy.head())
    df2.drop(["July 1, 2024 (est.)"], axis=1)
    print(df2.head())
    

    结果如下:

    KeyError  Traceback (most recent call last)
      File ~/Library/Python/3.9/lib/python/site-packages/pandas/core/indexes/base.py:3805, in Index.get_loc(self, key)
        3804 try:
     -> 3805     return self._engine.get_loc(casted_key)
        3806 except KeyError as err:
    KeyError: 'July 1, 2024 (est.)'
    
    1 回复  |  直到 4 月前
        1
  •  1
  •   wjandrea senderle    4 月前

    您需要指定要删除的列索引的级别。

    由于要删除的日期列位于级别1,因此需要明确提及。

    df2.drop(columns=["July 1, 2024 (est.)"], level=1, axis=1)