我正在运行一个变量是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
我想将其转换为数据帧,这样,我得到
product_id_y count
1159730 1
我试过这样做:
series1 = series1.to_frame()
但得错了结果
转换为dataframe后
6159402
product_id_y 1159730
count 1
完成重置索引后{i} series1 = series1.reset_index()
index 6159402
0 product_id_y 1159730
1 count 1
有没有其他方法可以做到这一点?
答案 0 :(得分:9)
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
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
答案 1 :(得分:2)
样品:
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]})
您可以通过将系列/数据框转换为字符串来打印:
> 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