【问题标题】:Transform Table from Narrow Table to Wide Table in Python在 Python 中将表从窄表转换为宽表
【发布时间】:2020-12-27 09:39:58
【问题描述】:

我在做一些代码时遇到了问题:

df_transform = df_restohours.pivot_table(index='placeID', columns='days', values='hours', aggfunc='sum')

我要转换表格,来自:

到:

我尝试运行该代码,但没有得到预期的表格

【问题讨论】:

标签: python pandas list dataframe datatable


【解决方案1】:

我认为 Pandas 没有任何内置方法来拆分列名,但您可以通过遍历列来实现目标。

试试这个代码:

import pandas as pd

dd = {'placeID':[13511,13522],
      'hours':['00:00-23:22','00:00-23:33'],
      'days':['Mon;Tue;Wed;Thu;Fri','Sat;Sun']
      }

df_restohours = pd.DataFrame(dd)

df = df_restohours.pivot_table(index='placeID', columns='days', values='hours', aggfunc='sum')

print(df_restohours.to_string(index=False))

df = df.rename_axis(None,axis='columns')  # remove 'days' label
df = df.reset_index()  # move index to column

for c in df.columns:
   for c1 in c.split(';')[1:]:   # copy to new columns
       df[c1] = df[c]
df = df.rename(columns={c:c.split(';')[0] for c in df.columns})  # rename original

print(df.to_string(index=False))

输出

 placeID        hours                 days
   13511  00:00-23:22  Mon;Tue;Wed;Thu;Fri
   13522  00:00-23:33              Sat;Sun


 placeID          Mon          Sat          Tue          Wed          Thu          Fri          Sun
   13511  00:00-23:22          NaN  00:00-23:22  00:00-23:22  00:00-23:22  00:00-23:22          NaN
   13522          NaN  00:00-23:33          NaN          NaN          NaN          NaN  00:00-23:33

【讨论】:

    猜你喜欢
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2021-09-01
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多