首页 > 解决方案 > 熊猫数据框和系列

问题描述

读取 excel 文件后,pandas 数据框为 30 行。它过滤到一行(过滤后总是一行),我怎样才能将数据框保留为数据框。在过滤器(删除行)之后,它将数据框转换为系列。

excel 文件 ppfileloc 在 4 月份有 30 行,对于选定的日期,它将始终是数据框中的一条记录。生成的数据框将重塑为系列。

#Following is the code and output in jupyter. 

df = pd.read_excel(ppfileloc)
df.set_index('Date',inplace=True)
date = 15
df1 = df.loc[date,:]
df2 = pd.DataFrame(df1)
df3 = df2.drop(labels=['Day', 'Sunrise', 'Sunset   ', 'SidTime    '])

df3.shape
# (8, 1)

#df3 command fetches the following as output
df3  

#         15
# Sun       000:37:56
# Moon      119:42:25
# Mars      045:36:33
# Mercury   333:14:41
# Jupiter   240:11:57
# Venus     329:01:24
# Saturn    266:12:49
# Rahu      087:52:24

如何转换df3为以行星和度数作为列标题的两列?

标签: pythonpandasjupyter-notebook

解决方案


如果你想将 a 转换Series为 a DataFrame,你可以这样做series.to_frame()。这接受一个name参数来说明如何命名数据框的单个列。这会将索引保留为索引。由于您希望将其作为一列,因此您还必须重置索引,然后根据需要重命名它。

df3.to_frame(name="degrees").reset_index().rename(columns={"index": "planet"})

推荐阅读