希望通过pandas同时对数据行列进行转置,使用pandas从数据读取数据方式:
import pandas as pd
from sqlalchemy import create_engine
sql = """
SELECT ts_code,end_date,revenue,oper_cost
FROM income where ts_code ='600002.SH' LIMIT 20
"""
df = pd.read_sql_query(sql, engine_ts)
从数据库读出来的原始数据格式:
ts_code | end_date | revenue | oper_cost |
---|---|---|---|
600002.SH | 20150930 | 539 | 434 |
600002.SH | 20150630 | 362 | 291 |
600002.SH | 20141231 | 768 | 608 |
600002.SH | 20150331 | 161 | 129 |
想转换成如下格式:
ts_code | ITEM | 20150930 | 20150630 | 20141231 | 20150331 |
---|---|---|---|---|---|
600007.SH | revenue | 539 | 362 | 768 | 161 |
600007.SH | oper_cost | 434 | 291 | 608 | 129 |
尝试过转置,但技术不行,以下代码,失败告终。
df = df.set_index(['revenue', 'oper_cost']) # 列转行
df = df.stack()
df.index = df.index.rename('temp_col1', level=2)
df.name = 'temp_col2'
df = df.reset_index()
df = df.set_index(['temp_col1', 'temp_col2']) # 行转列
df = df.unstack("temp_col2")
df = df.reset_index()
使用pandas的pivot_table就可以了,参考代码如下:
t='''
ts_code end_date revenue oper_cost
600002.SH 20150930 539 434
600002.SH 20150630 362 291
600002.SH 20141231 768 608
600002.SH 20150331 161 129
'''
import pandas as pd
import io
df=pd.read_table(io.StringIO(t))
new_df=pd.pivot_table(df,columns='end_date',values=['revenue','oper_cost'])
new_df=new_df.rename_axis([None], axis=1).reset_index().rename(columns={'index':'ITEM'},index=df['ts_code'][:len(new_df)])
print(new_df)
运行结果:
F:\2022\pythontest>t8
ITEM 20141231 20150331 20150630 20150930
600002.SH oper_cost 608 129 291 434
600002.SH revenue 768 161 362 539
如有帮助,请点击采纳采纳按钮给予支持~~
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!