Please help divide this multi-frame pandas into separates, that's code
import datetime as dt
import pandas as pd
import pandas_datareader.data as web
pd.set_option('display.max_columns', 500)
stocks=["1.HK","2.HK"]
start_time = dt.datetime(2022, 7, 1)
end_time = dt.datetime.now().date().isoformat()
df = web.DataReader(stocks, 'stooq', start_time, end_time)
print(df)
here is data retrieve
Attributes Close High Low Open Volume \
Symbols 2.HK 1.HK 2.HK 1.HK 2.HK 1.HK 2.HK 1.HK 2.HK
Date
2022-07-08 66.30 53.20 66.30 53.30 65.80 52.70 66.00 53.10 2495792
2022-07-07 65.95 52.80 65.95 52.80 65.25 52.15 65.50 52.50 3668691
2022-07-06 65.60 52.65 65.65 53.05 65.00 52.30 65.10 52.85 4684631
2022-07-05 65.95 53.15 66.00 54.20 65.60 53.00 65.90 53.70 2059494
2022-07-04 65.40 53.30 65.80 53.50 64.80 52.55 65.65 52.70 2732110
Attributes
Symbols 1.HK
Date
2022-07-08 2837712
2022-07-07 2426217
2022-07-06 3301780
2022-07-05 2887622
2022-07-04 3258099
I want to get separate frames (pd.dataframe) also it would be best to set columns names as: Close, High, Low, Open, Volume; and Date as a index. df_1HK
Date Close High Low Open Volume
2022-07-08 53.20 53.30 52.70 53.10 2837712
2022-07-07 52.80 52.80 52.15 52.50 2426217
2022-07-06 52.65 53.05 52.30 52.85 3301780
2022-07-05 53.15 54.20 53.00 53.70 2887622
2022-07-04 53.30 53.50 52.55 52.70 3258099
And there df_2HK
Date Close High Low Open Volume
2022-07-08 66.30 66.30 65.80 66.00 2495792
2022-07-07 65.95 65.95 65.25 65.50 3668691
2022-07-06 65.60 65.65 65.00 65.10 4684631
2022-07-05 65.95 66.00 65.60 65.90 2059494
2022-07-04 65.40 65.80 64.80 65.65 2732110
Thank You!
CodePudding user response:
DataFrame.xs
df1 = df.xs('1.HK', level=1, axis=1)
df2 = df.xs('2.HK', level=1, axis=1)
Or if you have multiple stocks then you can use a dictionary to store the corresponding dataframes
d = {s: df.xs(s, level=1, axis=1) for s in stocks}
>>> df1
Attributes Close High Low Open Volume
Date
2022-07-08 53.20 53.30 52.70 53.10 2837712
2022-07-07 52.80 52.80 52.15 52.50 2426217
2022-07-06 52.65 53.05 52.30 52.85 3301780
2022-07-05 53.15 54.20 53.00 53.70 2887622
2022-07-04 53.30 53.50 52.55 52.70 3258099
>>> df2
Attributes Close High Low Open Volume
Date
2022-07-08 66.30 66.30 65.80 66.00 2495792
2022-07-07 65.95 65.95 65.25 65.50 3668691
2022-07-06 65.60 65.65 65.00 65.10 4684631
2022-07-05 65.95 66.00 65.60 65.90 2059494
2022-07-04 65.40 65.80 64.80 65.65 2732110