Python 使用系列索引作为列的熊猫系列到数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40224319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:18:42  来源:igfitidea点击:

pandas Series to Dataframe using Series indexes as columns

pythonpandas

提问by Jialin Zou

I have a Series, like this:

我有一个系列,像这样:

series = pd.Series({'a': 1, 'b': 2, 'c': 3})

I want to convert it to a dataframe like this:

我想将其转换为这样的数据帧:

    a   b   c
0   1   2   3

pd.Series.to_framedoes't work, it got result like,

pd.Series.to_frame不起作用,结果如下,

    0
a   1
b   2
c   3

How to construct a DataFrame from Series, with index of Series as columns?

如何从 Series 构造 DataFrame,以 Series 的索引为列?

回答by PJay

You can also try this :

你也可以试试这个:

df = DataFrame(series).transpose()

Using the transpose() function you can interchange the indices and the columns. The output looks like this :

使用 transpose() 函数,您可以交换索引和列。输出如下所示:

    a   b   c
0   1   2   3

回答by cs95

You don't need the transposition step, just wrap your Series inside a list and pass it to the DataFrameconstructor:

您不需要转置步骤,只需将您的系列包装在一个列表中并将其传递给DataFrame构造函数:

pd.DataFrame([series])

   a  b  c
0  1  2  3


Alternatively, call Series.to_frame, then transpose using the shortcut .T:

或者,调用Series.to_frame,然后使用快捷方式转置.T

series.to_frame().T

   a  b  c
0  1  2  3

回答by Amir Rezaei

you can also try this:

你也可以试试这个:

a = pd.Series.to_frame(series)

a = pd.Series.to_frame(series)

a['id'] = list(a.index)

a['id'] = list(a.index)

Explanation:
The 1st line convert the series into a single-column DataFrame.
The 2nd line add an column to this DataFrame with the value same as the index.

说明:
第一行将系列转换为单列 DataFrame。
第 2 行向此 DataFrame 添加一列,其值与索引相同。

回答by Pritesh Shrivastava

Try reset_index. It will convert your index into a column in your dataframe.

试试 reset_index。它会将您的索引转换为数据框中的一列。

df = series.to_frame().reset_index()