[英]How to convert a Pandas series into a dataframe
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.我看过有关如何将系列转换为数据框的教程/文档,但它们都只显示静态数据(通过手动将每个值输入到数组中),这对我来说不是一个选择,因为我我的数据框中有超过 200 万行。
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?如何将 Top10Customers 转换为数据框? 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语法frame = { 'Col 1': series1, 'Col 2': series2 }
不起作用,因为我只有 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:实际上type(TopCustomers)
是 pandas.core.series.Series 下面把它变成一个 DataFrame:
pd.DataFrame(TopCustomers)
Otherwise .to_frame()
works equally well as indicated above.否则.to_frame()
与上面指出的一样好用。
您可以使用.to_frame()
方法,它将把它变成一个pd.DataFrame
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.