在数据库里我们很容易实现行转列,但是有一个局限性就是列名一定要固定,否则就无法实现,但是在dataframe里有对应的函数可以很容易实现。
样例数据:
pubdate media cnt
2021-04-01 APP 2109
2021-04-01 微信 1297
2021-04-01 微博 1479
2021-04-02 APP 2719
2021-04-02 微信 1040
2021-04-02 微博 2699
2021-04-03 APP 2267
2021-04-03 微信 934
2021-04-03 微博 1581
2021-04-04 APP 1969
处理过程:
sql ='''select pubdate,pubtype,count(DISTINCT docid) as cnt
from report_download_result_combine_dazzle_202104
GROUP BY pubdate,pubtype
limit 10;
'''
df = pd.read_sql(sql, conn)
df_1 = df.set_index(["pubdate", "pubtype"])["cnt"]
df_2 = df_1.unstack()
df_2 = df_2.reset_index()
print(df_2)
最终结果:
pubtype pubdate APP 微信 微博
0 2021-04-01 2109.0 1297.0 1479.0
1 2021-04-02 2719.0 1040.0 2699.0
2 2021-04-03 2267.0 934.0 1581.0
3 2021-04-04 1969.0 NaN NaN