简体   繁体   中英

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.

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

使用Series.to_frame

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM