1 回答
TA贡献1860条经验 获得超8个赞
您正在寻找df.pivot
df = df.pivot(index='Name', columns=['Date', 'Label'], values='Price')
警告:如果任何名称-日期-标签组合重复(即出现在多行中),则会引发错误。使用pivot_table或更好groupby+unstack
如果Name、Date、 和Label在索引中,则使用unstack而不是pivot
使用示例数据更新
df = pd.DataFrame({
# 'A': [160, 457, 457, 482, 482, 482, 482, 423, 223, 506],
# 'B': ['8/27/2015 0:00','10/15/2015 0:00','10/15/2015 0:00','10/28/2015 0:00','10/28/2015 0:00','10/28/2015 0:00','10/28/2015 0:00','9/29/2015 0:00','9/9/2015 0:00','11/9/2015 0:00'],
'Date': ['8/28/2015 0:00','10/16/2015 0:00','10/16/2015 0:00','10/29/2015 0:00','10/29/2015 0:00','10/29/2015 0:00','10/29/2015 0:00','9/30/2015 0:00','9/10/2015 0:00','11/10/2015 0:00'],
# 'C': [5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
# 'D': [1271, 1825, 1825, 1455, 1455, 1455, 1455, 2522, 1385, 1765],
'Price': [1058, 1685, 1615, 1195, 1255, 1279, 1295, 2285, 1285, 1665],
'Label': [3, 3, 2, 1, 3, 4, 2, 2, 1, 4],
# 'E': [13, 127, 127, -1, -1, -1, -1, -1, -1, -1],
'Name': ['foo1','foo2','foo2','foo3','foo3','foo3','foo3','foo4','foo4','foo3'],
# 'F': [4, 4, 4, 3, 3, 3, 3, 3, 3, 3],
# 'G': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
# 'H': ['Friday','Friday','Friday','Thursday','Thursday','Thursday','Thursday','Wednesday','Thursday','Tuesday'],
# 'I': [213, 140, 210, 260, 200, 176, 160, 237, 100, 100],
# 'J': [16.758457907159716,7.671232876712329,11.506849315068493,17.869415807560138,13.745704467353955,12.096219931271474,10.996563573883162,9.397303727200637,7.220216606498194,5.6657223796034]
})
df.Date = pd.to_datetime(df.Date)
df = df.pivot(index='Name', columns=['Date', 'Label'], values='Price')
df = df.fillna(-1)
print(df)
输出
Date 2015-08-28 2015-10-16 2015-10-29 ... 2015-09-30 2015-09-10 2015-11-10
Label 3 3 2 1 ... 2 2 1 4
Name ...
foo1 1058.0 NaN NaN NaN ... NaN NaN NaN NaN
foo2 NaN 1685.0 1615.0 NaN ... NaN NaN NaN NaN
foo3 NaN NaN NaN 1195.0 ... 1295.0 NaN NaN 1665.0
foo4 NaN NaN NaN NaN ... NaN 2285.0 1285.0 NaN
[4 rows x 10 columns]
添加回答
举报