python - 在 Pandas 中,如何将 "long"表转换为 "wide and sparse"表?

标签 python pandas numpy dataframe sparse-matrix

我的术语很糟糕,所以这个术语值得解释一下。想象一下,我有一个像这样的 DataFrame(我称之为“长”表):

time       stock     price
---------------------------
13:03:00   AAPL      100.00
13:03:00   SPY       200.00
13:03:01   AAPL      100.01
13:03:02   SPY       200.01
13:03:03   SPY       200.02
.
.
.

我想将它转换成这样的 DataFrame(我称之为“宽而稀疏”表):

time       AAPL      SPY
---------------------------
13:03:00   100.00    200.00
13:03:01   100.01    Nan
13:03:02   Nan       200.01
13:03:03   Nan       200.02

很明显,这是一个相当大的转变。是否有执行此操作的内置函数?这似乎是一件很常见的事情。

谢谢!

最佳答案

您可以使用 pivot :

df = df.pivot(index='time', columns='stock', values='price')
print (df)
stock       AAPL     SPY
time                    
13:03:00  100.00  200.00
13:03:01  100.01     NaN
13:03:02     NaN  200.01
13:03:03     NaN  200.02

另一种解决方案 unstack :

df = df.set_index(['time', 'stock']).price.unstack()
print (df)
stock       AAPL     SPY
time                    
13:03:00  100.00  200.00
13:03:01  100.01     NaN
13:03:02     NaN  200.01
13:03:03     NaN  200.02

但是如果得到:

ValueError: Index contains duplicate entries, cannot reshape

有必要用pivot_table带有一些聚合函数,默认 np.mean

print (df)
       time stock   price
0  13:03:00  AAPL  100.00
1  13:03:00   SPY  200.00
2  13:03:01  AAPL  100.01
3  13:03:02   SPY  200.01
4  13:03:03   SPY  200.02
5  13:03:03   SPY  500.02 <- duplicates for same time and stock 


df = df.pivot_table(index='time', columns='stock', values='price')
print (df)
stock       AAPL     SPY
time                    
13:03:00  100.00  200.00
13:03:01  100.01     NaN
13:03:02     NaN  200.01
13:03:03     NaN  350.02

重复 timestock 的另一种可能解决方案:

df = df.groupby(['time', 'stock']).price.mean().unstack()
print (df)
stock       AAPL     SPY
time                    
13:03:00  100.00  200.00
13:03:01  100.01     NaN
13:03:02     NaN  200.01
13:03:03     NaN  350.02

关于python - 在 Pandas 中,如何将 "long"表转换为 "wide and sparse"表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41922755/

相关文章:

python - 扩展 Pandas 数据框的简单/有效方法

Python Pandas 从两行创建共同出现矩阵

python - 将 SKLearn 癌症数据集加载到 Pandas DataFrame 中

python - 如何控制和测试 "invalid value encountered in..."错误?

python - OpenCV python:solvePnP ValueError:太多值无法解压

python - 如何在 Python 包中导入符号?

python - 使用 django ORM 进行高级排序

python - 使用 SciPy 查找多维标量函数根的最佳方法

python - Pandas 按日期时间分组

python - 索引错误: shape mismatch: indexing arrays could not be broadcast together with shapes