Gavrk
Gavrk

Reputation: 325

Pandas Series to Pandas Dataframe

I have an object <class 'pandas.core.series.Series'> that looks like this:

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

Created by DataFrame(some_cfd).transpose().sum(axis=1). Now I need to transform it so it would look as follows:

                              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

After hours of reading Pandas documentation I still can't figure out how to do that. It should be a <class 'pandas.core.frame.DataFrame'> with a single-level indexing. Each time is use reset_index() it created some new (index?) column, and using set_index('index') creates a two-level column indexing that I don't need.

I can imagine there area many corresponding cases, so sorry in advance if it already was answered somewhere, but so far I have not find the solution. Any help would be appreciated.

Upvotes: 2

Views: 1832

Answers (2)

jezrael
jezrael

Reputation: 862396

Use Series.to_frame:

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

Upvotes: 1

Giorgos Myrianthous
Giorgos Myrianthous

Reputation: 39790

to_frame can be used to convert a Series to DataFrame.

series = DataFrame(some_cfd).transpose().sum(axis=1)

# The provided name (1) will substitute for the series name
df = series.to_frame(1)

And the output should be:

>>> 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

Upvotes: 2

Related Questions