【问题标题】:Pandas Series to Pandas Dataframe熊猫系列到熊猫数据框
【发布时间】:2020-06-03 13:36:24
【问题描述】:

我有一个对象<class 'pandas.core.series.Series'>,看起来像这样:

DataFrame(cfd_appr).transpose().sum(axis=1)
2022.12.06_Bild 2.txt     524.0
2022.12.06_Bild 3.txt     620.0
2022.12.06_Bild 4.txt     535.0
2022.12.06_Bild 5.txt     799.0
2022.12.06_Bild 6.txt    1032.0
2022.12.06_Bild 8.txt       4.0
dtype: float64

DataFrame(some_cfd).transpose().sum(axis=1) 创建。现在我需要对其进行改造,使其如下所示:

                              1
2022.12.06_Bild 2.txt     524.0
2022.12.06_Bild 3.txt     620.0
2022.12.06_Bild 4.txt     535.0
2022.12.06_Bild 5.txt     799.0
2022.12.06_Bild 6.txt    1032.0
2022.12.06_Bild 8.txt       4.0

阅读Pandas documentation 几个小时后,我仍然不知道该怎么做。它应该是具有单级索引的<class 'pandas.core.frame.DataFrame'>。每次使用 reset_index() 它创建了一些新的(索引?)列,使用 set_index('index') 创建了一个我不需要的两级列索引。

我可以想象那里有很多相应的案例,如果已经在某个地方回答了,请提前抱歉,但到目前为止我还没有找到解决方案。任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas dataframe indexing series


    【解决方案1】:

    使用Series.to_frame:

    pd.DataFrame(cfd_appr).transpose().sum(axis=1).to_frame(1)
    

    【讨论】:

      【解决方案2】:

      to_frame 可用于将Series 转换为DataFrame

      series = DataFrame(some_cfd).transpose().sum(axis=1)
      
      # The provided name (1) will substitute for the series name
      df = series.to_frame(1)
      

      输出应该是:

      >>> print(df)
      
                                    1
      2022.12.06_Bild 2.txt     524.0
      2022.12.06_Bild 3.txt     620.0
      2022.12.06_Bild 4.txt     535.0
      2022.12.06_Bild 5.txt     799.0
      2022.12.06_Bild 6.txt    1032.0
      2022.12.06_Bild 8.txt       4.0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-12
        • 2022-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-30
        • 1970-01-01
        相关资源
        最近更新 更多