在 python 中转换帧 pandas
Convert frame pandas in python
我从 pandas 数据读取器收到如下输出:
Date AAPL ACN
0 2016-11-21 111.730003 119.680000
1 2016-11-22 111.800003 119.480003
2 2016-11-23 111.230003 119.820000
3 2016-11-25 111.790001 120.739998
4 2016-11-28 111.570000 120.760002
框架看起来像什么:
Date Minor Adj Close
0 2016-11-21 AAPL 111.730003
1 2016-11-22 AAPL 111.800003
2 2016-11-23 AAPL 111.230003
3 2016-11-25 AAPL 111.790001
4 2016-11-28 AAPL 111.570000
0 2016-11-21 ACN 119.680000
1 2016-11-22 ACN 119.480003
2 2016-11-23 ACN 119.820000
3 2016-11-25 ACN 120.739998
4 2016-11-28 ACN 120.760002
如何转换收到上述输出的代码?代码如下所示:
import pandas_datareader.data as pdr
DataLevels = pdr.DataReader(['ACN','AAPL'], 'yahoo', '2016-11-19', '2016-12-1')
DataLevels = DataLevels['Adj Close'].reset_index()
DataLevels.rename(columns={'minor': ['ACN','AAPL'], 'Adj Close': 'Adj Close'}, inplace=True)
print(DataLevels)
使用 melt
将 DF
从宽格式重塑为长格式:
pd.melt(df, id_vars=['Date'], value_name='Adj Close', var_name='Minor')
我从 pandas 数据读取器收到如下输出:
Date AAPL ACN
0 2016-11-21 111.730003 119.680000
1 2016-11-22 111.800003 119.480003
2 2016-11-23 111.230003 119.820000
3 2016-11-25 111.790001 120.739998
4 2016-11-28 111.570000 120.760002
框架看起来像什么:
Date Minor Adj Close
0 2016-11-21 AAPL 111.730003
1 2016-11-22 AAPL 111.800003
2 2016-11-23 AAPL 111.230003
3 2016-11-25 AAPL 111.790001
4 2016-11-28 AAPL 111.570000
0 2016-11-21 ACN 119.680000
1 2016-11-22 ACN 119.480003
2 2016-11-23 ACN 119.820000
3 2016-11-25 ACN 120.739998
4 2016-11-28 ACN 120.760002
如何转换收到上述输出的代码?代码如下所示:
import pandas_datareader.data as pdr
DataLevels = pdr.DataReader(['ACN','AAPL'], 'yahoo', '2016-11-19', '2016-12-1')
DataLevels = DataLevels['Adj Close'].reset_index()
DataLevels.rename(columns={'minor': ['ACN','AAPL'], 'Adj Close': 'Adj Close'}, inplace=True)
print(DataLevels)
使用 melt
将 DF
从宽格式重塑为长格式:
pd.melt(df, id_vars=['Date'], value_name='Adj Close', var_name='Minor')