所以我想使用 Pandas DataFrame 在我的 Excel 工作表(已经存在的数据)中创建一个额外的索引/额外的列。这就是我的意思:
图 1(我的代码输出的内容):
图 2(我希望我的代码输出什么):
这是我的图片 1 代码:
import pandas as pd
# Create a Pandas dataframe from the data.
df = pd.DataFrame([['a', 'b'], ['c', 'd']],
index=['row 1', 'row 2'],
columns=['col 1', 'col 2'])
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
# Close the Pandas Excel writer and output the Excel file.
writer.close()
有没有办法做到这一点?
pd.MultiIndex.from_arrays
:
new_idx = pd.Index(['data_type_1', 'date_type_2'])
out = df.set_index(pd.MultiIndex.from_arrays([df.index, new_idx]))
out.to_excel('pandas_simple.xlsx')
print(out)
# Output
col 1 col 2
row 1 data_type_1 a b
row 2 date_type_2 c d
更新
也许你想更喜欢:
new_idx = pd.Index(['data_type_1', 'date_type_2'])
mi = pd.MultiIndex.from_product([df.index, new_idx])
out = df.reindex(df.index.repeat(len(new_idx))).set_index(mi)
print(out)
# Output
col 1 col 2
row 1 data_type_1 a b
date_type_2 a b
row 2 data_type_1 c d
date_type_2 c d