Python pandas 从长转向宽

标签 python pandas dataframe pivot-table reshape

我的数据目前是长格式。下面是一个示例:

     Stock         Date      Time     Price     Year
       AAA   2001-01-05  15:20:09     2.380     2001
       AAA   2002-02-23  10:13:24     2.440     2002
       AAA   2002-02-27  17:17:55     2.460     2002
       BBB   2006-05-13  16:03:49     2.780     2006
       BBB   2006-10-04  10:33:10     2.800     2006

我想通过“股票”和“年份”将其 reshape 为宽格式,如下所示:

     Stock   Year       Date1        Time1    Price1        Date2      Time2   Price2
       AAA   2001  2001-01-05     15:20:09     2.380
       AAA   2002  2002-02-23     10:13:24     2.440   2002-02-27   17:17:55    2.460
       BBB   2006  2006-05-13     16:03:49     2.780   2006-10-04   10:33:10    2.800

我尝试了此处发布的解决方案 Pandas long to wide reshape并拥有这个:

df['idx'] = df.groupby(['Stock', 'Year']).cumcount()

df['date_idx'] = 'date_' + df.idx.astype(str)
df['time_idx'] = 'time_' + df.idx.astype(str)
df['price_idx'] = 'price_' + df.idx.astype(str)

date = df.pivot(index=['Stock', 'Year'], columns='date_idx', values='Date')
time = df.pivot(index=['Stock', 'Year'], columns='time_idx', values='Time')
price = df.pivot(index=['Stock', 'Year'], columns='price_idx', values='Price')

reshape = pd.concat([date, time, price], axis=1)

但是最后一行给我这个错误:

ValueError: Wrong number of items passed 15624, placement implies 2

我的代码哪里出错了?还是有另一种更简洁的方法来进行这种 reshape ?

最佳答案

我想你可以使用 pivot_table ,但需要一些 aggfunc。我选择 first,因为使用默认的 np.meandatetime 有问题。

更好的样本解释是heredocs .

解决方案1:

df['idx'] = (df.groupby(['Stock', 'Year']).cumcount() + 1).astype(str)

df1 = (df.pivot_table(index=['Stock', 'Year'], 
                      columns=['idx'], 
                      values=['Date', 'Time', 'Price'], 
                      aggfunc='first'))
df1.columns = [''.join(col) for col in df1.columns]
df1 = df1.reset_index()
print (df1)
  Stock  Year       Date1       Date2     Time1     Time2 Price1 Price2
0   AAA  2001  2001-01-05        None  15:20:09      None   2.38   None
1   AAA  2002  2002-02-23  2002-02-27  10:13:24  17:17:55   2.44   2.46
2   BBB  2006  2006-05-13  2006-10-04  16:03:49  10:33:10   2.78    2.8

然后您可以转换为float price 列和to_datetime 日期列:

cols = df1.columns[df1.columns.str.contains('Price')]
df1[cols] = df1[cols].astype(float)

cols = df1.columns[df1.columns.str.contains('Date')]
df1[cols] = df1[cols].apply(pd.to_datetime)


print (df1)
  Stock  Year      Date1      Date2     Time1     Time2  Price1  Price2
0   AAA  2001 2001-01-05        NaT  15:20:09      None    2.38     NaN
1   AAA  2002 2002-02-23 2002-02-27  10:13:24  17:17:55    2.44    2.46
2   BBB  2006 2006-05-13 2006-10-04  16:03:49  10:33:10    2.78    2.80

print (df1.dtypes)
Stock             object
Year               int64
Date1     datetime64[ns]
Date2     datetime64[ns]
Time1             object
Time2             object
Price1           float64
Price2           float64

解决方案2:

df['idx'] = df.groupby(['Stock', 'Year']).cumcount() + 1

df['date_idx'] = 'date_' + df.idx.astype(str)
df['time_idx'] = 'time_' + df.idx.astype(str)
df['price_idx'] = 'price_' + df.idx.astype(str)

date = df.pivot_table(index=['Stock', 'Year'], columns='date_idx', values='Date', aggfunc='first')
time = df.pivot_table(index=['Stock', 'Year'], columns='time_idx', values='Time', aggfunc='first')
price = df.pivot_table(index=['Stock', 'Year'], columns='price_idx', values='Price', aggfunc='first')

reshape = pd.concat([date, time, price], axis=1).reset_index()
print (reshape)
  Stock  Year      date_1      date_2    time_1    time_2  price_1  price_2
0   AAA  2001  2001-01-05        None  15:20:09      None     2.38      NaN
1   AAA  2002  2002-02-23  2002-02-27  10:13:24  17:17:55     2.44     2.46
2   BBB  2006  2006-05-13  2006-10-04  16:03:49  10:33:10     2.78     2.80

关于Python pandas 从长转向宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37653779/

相关文章:

python - 为什么在使用命令行设置本地时间时使用 timedatectl 设置 UTC 时间从 python 设置时间?

python pandas groupby和过滤函数删除候选人姓名,无需两次预测

python - 将 0 或 1 的实例计数到系列中

python - 根据值以批量方式删除 pandas 数据帧行和列

python - 浮点比较不会产生 pandas 中的预期输出

python - 比较两个不同格式的列表

python - 每个 MayaVi 异常都会挂起我的 ipython 解释器

python - 为什么给定数据类型 "range"的变量在使用 "list"函数时仍然显示为 "type"?

python - 将标量值分配给空 DataFrame 似乎没有做任何事情

python - 为多索引数据帧的第一行分配一个值