2

I've been running some groupings on a dataframe that I have and saving the results in variables. However, I just noticed that the variables are actually being saved as series rather than dataframes.

I've seen tutorials/docs on how to convert a series to a dataframe, but all of them show only static data (by manually typing each of the values into an array), and this isn't an option for me, because I have over 2 million rows in my data frame.

So if I have

TopCustomers = raw_data.groupby(raw_data['Company'])['Total Records'].sum()
Top10Customers = TopCustomers.sort_values().tail(10)

How can I turn Top10Customers into a dataframe? I need it because not all plots work with series.

The syntax frame = { 'Col 1': series1, 'Col 2': series2 } doesn't work because I only have 1 series

4
  • I think you can use the following command: pd.DataFrame(TopCustomers.sort_values().tail(10)) Commented Dec 4, 2019 at 20:22
  • Top10Customers.to_frame()? Commented Dec 4, 2019 at 20:22
  • @QuangHoang I think that method is not aligning the columns properly, maybe its just visual but Im noticing that by using that, the 'Total Records' is position way above the 'companies' column. I used Top10CustomersDF = pandas.DataFrame({'Customers':Top10Customers.index, 'Total Records':Top10Customers.values}) and it got aligned Commented Dec 4, 2019 at 20:31
  • 1
    That's because companies is currently the index. If so, what you want is Top10Customers.reset_index(). Commented Dec 4, 2019 at 20:32

2 Answers 2

1

Here a small example with data:

import pandas as pd
raw_data = pd.DataFrame({'Company':['A', 'A','B', 'B', 'C', 'C'], 'Total Records':[2,3,6,4,5,10]})
TopCustomers = raw_data.groupby(raw_data['Company'])['Total Records'].sum()

Indeed type(TopCustomers) is pandas.core.series.Series The following turns it in a DataFrame:

pd.DataFrame(TopCustomers)

Otherwise .to_frame() works equally well as indicated above.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the .to_frame() method and it will turn it into a pd.DataFrame.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.