Pandas DataFrame:转换为两级索引

时间:2018-02-22 01:41:58

标签: pandas dataframe

两个数据帧:

enter image description here

自动收报机名称各为FLQEFLQG

我想要生成的是低于数据帧格式

enter image description here

我不知道我必须为Google搜索选择哪个关键字来查找如何执行此操作,这就是我在stackoverflow中发布问题的原因。

需要你的帮助。

感谢

2 个答案:

答案 0 :(得分:0)

也许是这样的:

# Recreate DafaFrames
dates = ['2017-12-24', '2017-12-25', '2017-12-26']
df1 = {'open': [1, 2, 3]}
df2 = {'open': [4, 5, 6]}
df1 = pd.DataFrame(df1, index=dates)
df2 = pd.DataFrame(df2, index=dates)

##################

# Set names
df1_name = 'FLQE'
df2_name = 'FLQG'

# Create new MultiIndex for df1 (using date and name)
df1_new_idx = pd.MultiIndex.from_tuples(list(zip(df1.index, [df1_name] * len(df1))))
# Set the new index
df1 = df1.set_index(df1_new_idx)

# Create new MultiIndex for df2 (using date and name)
df2_new_idx = pd.MultiIndex.from_tuples(list(zip(df2.index, [df2_name] * len(df2))))
# Set the new index
df2 = df2.set_index(df2_new_idx)

# Concatenate both DataFrames
merged = pd.concat([df1, df2])

# Sort them by index
merged.sort_index()

答案 1 :(得分:0)

如果你只是想要那种' 格式'正如你强调的那样......(假设两个dfs是df1,df2。)

df1['Equity'] = 'AAAA'
df2['Equity'] = 'BBBB'

df_ = pd.concat([df, df2], axis=0).groupby(['date', 'Equity']).nth(0)
df_

enter image description here

df_.index

MultiIndex(levels=[[2013-01-01 00:00:00, 2013-01-02 00:00:00, 2013-01-03 00:00:00], ['AAAA', 'BBBB']],
           labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],
           names=['date', 'Equity'])