将 pandas.core.series.Series 转换为具有适当列值的数据框 python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41054485/
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
Converting pandas.core.series.Series to dataframe with appropriate column values python
提问by Shubham R
i'm running a function in which a variable is of pandas.core.series.Series type.
我正在运行一个函数,其中一个变量是 pandas.core.series.Series 类型。
type of the series shown below.
<class 'pandas.core.series.Series'>
product_id_y 1159730
count 1
Name: 6159402, dtype: object
i want to convert this into a dataframe,such that, i get
我想把它转换成一个数据框,这样,我得到
product_id_y count
1159730 1
i tried doing this:
我试过这样做:
series1 = series1.to_frame()
but getting wrong result
但得到错误的结果
after converting to dataframe
转换为数据框后
6159402
product_id_y 1159730
count 1
after doing reset index i'e series1 = series1.reset_index()
执行重置索引后,我 series1 = series1.reset_index()
index 6159402
0 product_id_y 1159730
1 count 1
is there anny other way to do this??
有没有其他方法可以做到这一点?
回答by jezrael
You was very close, first to_frame
and then transpose by T
:
s = pd.Series([1159730, 1], index=['product_id_y','count'], name=6159402)
print (s)
product_id_y 1159730
count 1
Name: 6159402, dtype: int64
df = s.to_frame().T
print (df)
product_id_y count
6159402 1159730 1
df = s.rename(None).to_frame().T
print (df)
product_id_y count
0 1159730 1
Another solution with DataFrame
constructor:
DataFrame
构造函数的另一个解决方案:
df = pd.DataFrame([s])
print (df)
product_id_y count
6159402 1159730 1
df = pd.DataFrame([s.rename(None)])
print (df)
product_id_y count
0 1159730 1
回答by Abhijay Ghildyal
Sample:
样本:
import pandas as pd
df = pd.DataFrame({'Name': ['Will','John','John','John','Alex'],
'Payment': [15, 10, 10, 10, 15],
'Duration': [30, 15, 15, 15, 20]})
You can print by converting the series/dataframe to string:
您可以通过将系列/数据帧转换为字符串来打印:
> print (df.to_string())
Duration Name Payment
0 30 Will 15
1 15 John 10
2 15 John 10
3 15 John 10
4 20 Alex 15
> print (df.iloc[1].to_string())
Duration 15
Name John
Payment 10