使用适当的列值python将pandas.core.series.Series转换为dataframe

Shu*_*m R 11 python pandas

我正在运行一个变量是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
Run Code Online (Sandbox Code Playgroud)

我想将其转换为数据帧,这样,我得到

product_id_y    count
1159730           1
Run Code Online (Sandbox Code Playgroud)

我试过这样做:

series1 = series1.to_frame()
Run Code Online (Sandbox Code Playgroud)

但得到错误的结果

转换为数据帧后

              6159402
product_id_y  1159730
count               1
Run Code Online (Sandbox Code Playgroud)

做完重置索引之后我就是 series1 = series1.reset_index()

           index  6159402
 0  product_id_y  1159730
 1         count        1
Run Code Online (Sandbox Code Playgroud)

还有其他方法吗?

jez*_*ael 15

你非常接近,先是to_frame通过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
Run Code Online (Sandbox Code Playgroud)
df = s.rename(None).to_frame().T
print (df)
   product_id_y  count
0       1159730      1
Run Code Online (Sandbox Code Playgroud)

DataFrame构造函数的另一个解决方案

df = pd.DataFrame([s])
print (df)
         product_id_y  count
6159402       1159730      1
Run Code Online (Sandbox Code Playgroud)
df = pd.DataFrame([s.rename(None)])
print (df)
   product_id_y  count
0       1159730      1
Run Code Online (Sandbox Code Playgroud)

  • 更好的`df.reset_index(drop=True)` (2认同)