数据库表格如下:
ts_code | end_date | bz_item | bz_sales | bz_profit | bz_cost | curr_type | update_flag |
---|---|---|---|---|---|---|---|
600002.SH | 20191231 | 中国大陆 | 1102.81 | 204.55 | 898.26 | CNY | 0 |
600002.SH | 20191231 | 国外 | 172.28 | 36.97 | 135.31 | CNY | 0 |
600002.SH | 20200630 | 中国大陆 | 439.40379 | 0 | 0 | CNY | 0 |
600002.SH | 20200630 | 国外 | 92.96429 | 0 | 0 | CNY | 0 |
600002.SH | 20201231 | 中国大陆 | 1156.44 | 176.02 | 980.42 | CNY | 0 |
600002.SH | 20201231 | 国外 | 216.41 | 56.55 | 159.86 | CNY | 0 |
600002.SH | 20201231 | 其他业务(地区) | 0.00056 | 0.78751 | -0.78695 | CNY | 0 |
600002.SH | 20210630 | 中国大陆 | 508.93198 | 0 | 0 | CNY | 0 |
600002.SH | 20210630 | 国外 | 116.34514 | 0 | 0 | CNY | 0 |
希望通过pandas转成如下:
ts_code | bz_item | ITEM | 20191231 | 20200630 | 20201231 | 20210630 |
---|---|---|---|---|---|---|
600002.SH | 中国大陆 | bz_sales | 1102.81 | 439.40379 | 216.41 | 508.93198 |
600002.SH | 中国大陆 | bz_profit | 204.55 | 0 | 56.55 | 0 |
600002.SH | 中国大陆 | bz_cost | 898.26 | 0 | 159.86 | 0 |
600002.SH | 国外 | bz_sales | 172.28 | 92.96429 | 0.00056 | 116.34514 |
600002.SH | 国外 | bz_profit | 36.97 | 0 | 0.78751 | 0 |
600002.SH | 国外 | bz_cost | 135.31 | 0 | -0.78695 | 0 |
python语句如下:
sql = """
SELECT ts_code,end_date,bz_item,bz_sales,bz_profit,bz_cost,curr_type,update_flag
FROM fina_mainbz_p where ts_code ='600002.SH' order by end_date asc
"""
print(sql)
df = pd.read_sql_query(sql, engine_ts)
new_df = pd.pivot_table(df, columns='end_date', values=item_list)
new_df = new_df.rename_axis([None], axis=1).reset_index().rename(
columns={'index': 'ITEM'}).set_index(['ITEM'])
# 增加 产品或地区bz_item字段
new_df = new_df.rename_axis([None], axis=1).reset_index().rename(
columns={'index': 'ITEM'}, index=df['bz_item'][:len(new_df)])
print(new_df)
# 保存到csv
new_df.to_csv(r"D:/Personal/Desktop/ts_" +
str(int(time.time())) + ".csv", encoding='utf_8_sig')
但无法达到想要的输出结果,不知道pivot_table该怎么操作?