【问题标题】:Python: How to loop through hierarchical columns?Python:如何遍历分层列?
【发布时间】:2021-12-23 10:36:05
【问题描述】:

我有以下数据框:

df=pd.DataFrame(index = ['2018-01-01','2018-01-02','2018-01-03','2018-01-04'])
df["ticker"] = ['TSLA', 'TSLA', 'IBM', 'IBM']
df["price"] = ['1000', '1200', '101', '108']
df["volume"] = ['100000', '123042', '1087878', '108732']
df["marketcap"] = ['1.2T', '1.4T', '30B', '35B']
df.index.rename('Date', inplace=True)
df.set_index('ticker', append=True).unstack('ticker').swaplevel(axis=1).sort_index(axis=1,level=0, sort_remaining=False)
df:
                 TSLA                              IBM         
                 price  volume  marketcap          price  volume    marketcap
          Date              
    2018-01-01   1000   100000  1.2T               NaN    NaN       NaN
    2018-01-02   1200   123042  1.4T               NaN    NaN       NaN
    2018-01-03   NaN    NaN     NaN                101    1087878   30B
    2018-01-04   NaN    NaN     NaN                108    108732    35B

如何遍历代码(即 TSLA)并从中仅获取每个日期的价格列? 所以是这样的:

  for col in df.columns(level=0):
      for i in df.index:
          if df.columns(level=1)=="price":
              df_price=df[col].loc[i]

df_price 看起来像这样:

              TSLA
      Date 
2018-01-01    1000

其余的价格和代码以此类推。 谢谢。

【问题讨论】:

  • 如果你想要所有列的价格,那么这个df.loc[:,pd.IndexSlice[:, 'price']]应该这样做,是你想要的吗?
  • df.loc(axis=1)[:, 'price']df.loc[:, df.columns.isin(['price'], level=1)] 是其他选项。
  • df.loc(axis=1)[('TSLA', 'price')]
  • 谢谢大家! @Ben.T 和 Henry,您的解决方案都有效

标签: python pandas dataframe loops hierarchy


【解决方案1】:

可能是这样的?

df.reset_index(inplace=True)
pd.pivot_table(df,index=["Date"], columns=["ticker"], values=["price"])


            price
ticker      IBM     TSLA
Date        
2018-01-01  NaN     1000.0
2018-01-02  NaN     1200.0
2018-01-03  101.0   NaN
2018-01-04  108.0   NaN

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-26
    • 2013-09-12
    • 2022-11-17
    • 1970-01-01
    • 2013-02-18
    • 2016-12-08
    • 1970-01-01
    相关资源
    最近更新 更多