csv 如何在python中水平旋转一个也有多列值的表[重复]

13z8s7eq  于 11个月前  发布在  Python
关注(0)|答案(1)|浏览(111)

这个问题已经有答案了

How can I pivot a dataframe?(5个回答)
13天前关闭
现在我有一个这样的表格:

Ticker  Financial Ratio                  2001     2002    2003    
  ARKR    Net Profit Margin                -0.1931  0.052   -0.0187
  ARKR    Return on Assets                 0        0       0
  ARKR    Current Ratio                    1.3419     1.2096  0.7031
  ARMK    Net Profit Margin                -0.1931  0.052   -0.0187
  ARMK    Return on Assets                 0        0       0
  ARMK    Current Ratio                    1.3419     1.2096  0.7031

字符串
我希望将其转换为:

Ticker  2001 Net Profit Margin  2001 Return on Assets  2001 Current Ratio  2002 Net Profit Margin...
  ARKR    -0.1931                 0                      1.3419              0.052  
  ARMK    -0.1931                 0                      1.3419              0.052


仅保持股票代码垂直
到目前为止我有代码:

pre_horizontal_df = pd.read_csv('database_raw.csv')
  pre_horizontal_df['period'] = pre_horizontal_df.2001.astype(str)
  df1 = pre_horizontal_df.groupby(['ticker']).unstack()
  print (df1)


但我知道这是不正确的,这个水平轴可以在python df / pandas中完成吗?

im9ewurl

im9ewurl1#

您可以尝试DataFrame.pivot,只需跳过定义values=

out = df.pivot(index="Ticker", columns="Financial Ratio")
out.columns = [f"{year} {desc}" for year, desc in out.columns]
print(out.reset_index())

字符串
打印:

Ticker  2001 Current Ratio  2001 Net Profit Margin  2001 Return on Assets  2002 Current Ratio  2002 Net Profit Margin  2002 Return on Assets  2003 Current Ratio  2003 Net Profit Margin  2003 Return on Assets
0   ARKR              1.3419                 -0.1931                    0.0              1.2096                   0.052                    0.0              0.7031                 -0.0187                    0.0
1   ARMK              1.3419                 -0.1931                    0.0              1.2096                   0.052                    0.0              0.7031                 -0.0187                    0.0

相关问题