熊猫系列到熊猫数据框

时间:2020-02-19 11:31:29

标签: python pandas dataframe indexing series

我有一个对象<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')则会创建一个我不需要的两级列索引。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

使用Series.to_frame

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