python - 熊猫数据框和系列
问题描述
读取 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
为以行星和度数作为列标题的两列?
解决方案
如果你想将 a 转换Series
为 a DataFrame
,你可以这样做series.to_frame()
。这接受一个name
参数来说明如何命名数据框的单个列。这会将索引保留为索引。由于您希望将其作为一列,因此您还必须重置索引,然后根据需要重命名它。
df3.to_frame(name="degrees").reset_index().rename(columns={"index": "planet"})
推荐阅读
- javascript - 我无法在 React 上实现 Lightbox Gallery
- azure-ad-b2c - Azure 广告 b2c 帐户锁定
- scala - Scala 隐式扩展接口
- reactjs - 无法在网站上显示图像 Webpack React-dom 意外语法
- python - 它说“TypeError:__init__() 需要 4 个位置参数,但给出了 5 个”,但我不明白为什么(Python3)
- python - 程序获取数字 1-1000 的列表,将它们反转,将它们放入一个文件(称为 my_file)并将它们打印回 my_file
- python - 使用 Python 和 Tesseract OCR 解决验证码
- python - 国家和人口
- python - 无法将 get 方法与 Tkinter Text Widget 一起使用
- c# - ASP.NET Identity 的 UserManager 是否需要关闭或处置?