Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >用Python重组Dataframe

用Python重组Dataframe
EN

Stack Overflow用户
提问于 2015-06-17 09:25:46
回答 1查看 756关注 0票数 2

我已经从此Excel文件中的倒数第二个工作表中收集了数据,以及从5.5岁开始的最后一个工作表中的所有数据。我有密码能做到这一点。但是,我现在希望对dataframe进行结构调整,使其具有以下列,并且很难做到这一点:

我的密码在下面。

代码语言:javascript
运行
AI代码解释
复制
import urllib2
import pandas as pd
import os
import xlrd 

url = 'http://www.bankofengland.co.uk/statistics/Documents/yieldcurve/uknom05_mdaily.xls'
socket = urllib2.urlopen(url)

xd = pd.ExcelFile(socket)

#Had to do this based on actual sheet_names rather than index as there are some extra sheet names in xd.sheet_names
df1 = xd.parse('4. spot curve', header=None)
df1 = df1.loc[:, df1.loc[3, :] >= 5.5] #Assumes the maturity is always on the 4th line of the sheet
df2 = xd.parse('3. spot, short end', header=None)

bigdata = df1.append(df2,ignore_index = True)

编辑:Dataframe当前如下所示。不幸的是,当前的Dataframe相当混乱:

代码语言:javascript
运行
AI代码解释
复制
                       0    1   2   3         4         5         6   \
0                     NaN  NaN NaN NaN       NaN       NaN       NaN   
1                     NaN  NaN NaN NaN       NaN       NaN       NaN   
2                Maturity  NaN NaN NaN       NaN       NaN       NaN   
3                  years:  NaN NaN NaN       NaN       NaN       NaN   
4                     NaN  NaN NaN NaN       NaN       NaN       NaN   
5     2005-01-03 00:00:00  NaN NaN NaN       NaN       NaN       NaN   
6     2005-01-04 00:00:00  NaN NaN NaN       NaN       NaN       NaN
...                   ...  ...  ..  ..       ...       ...       ...   
5410  2015-04-20 00:00:00  NaN NaN NaN       NaN  0.367987  0.357069   
5411  2015-04-21 00:00:00  NaN NaN NaN       NaN  0.362478  0.352581

它有5440行和61列

但是,我希望数据格式是:

我认为列1,2,3,4,5和6包含收益率曲线数据。但是,我不确定与“成熟度年”相关的数据在当前DataFrame中的位置。

代码语言:javascript
运行
AI代码解释
复制
Date(which is the 2nd Column in the current Dataframe)    Update time(which would just be a column with datetime.datetime.now())    Currency(which would just be a column with 'GBP')    Maturity Date    Yield Data from SpreadSheet
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-17 13:47:45

我使用pandas.io.excel.read_excel函数从url读取xls。以下是清理英国收益率曲线数据集的一种方法。

注意:通过应用函数执行三次样条插值需要相当长的时间(在我的PC上大约2分钟)。它从大约100点插入到300点,逐行(总共2638点)。

代码语言:javascript
运行
AI代码解释
复制
from pandas.io.excel import read_excel
import pandas as pd
import numpy as np

url = 'http://www.bankofengland.co.uk/statistics/Documents/yieldcurve/uknom05_mdaily.xls'

# check the sheet number, spot: 9/9, short end 7/9
spot_curve = read_excel(url, sheetname=8)
short_end_spot_curve = read_excel('uknom05_mdaily.xls', sheetname=6)

# preprocessing spot_curve
# ==============================================
# do a few inspection on the table
spot_curve.shape
spot_curve.iloc[:, 0]
spot_curve.iloc[:, -1]
spot_curve.iloc[0, :]
spot_curve.iloc[-1, :]
# do some cleaning, keep NaN for now, as forward fill NaN is not recommended for yield curve
spot_curve.columns = spot_curve.loc['years:']
spot_curve.columns.name = 'years'
valid_index = spot_curve.index[4:]
spot_curve = spot_curve.loc[valid_index]
# remove all maturities within 5 years as those are duplicated in short-end file
col_mask = spot_curve.columns.values > 5
spot_curve = spot_curve.iloc[:, col_mask]

# now spot_curve is ready, check it
spot_curve.head()
spot_curve.tail()
spot_curve.shape

spot_curve.shape
Out[184]: (2715, 40)

# preprocessing short end spot_curve
# ==============================================
short_end_spot_curve.columns = short_end_spot_curve.loc['years:']
short_end_spot_curve.columns.name = 'years'
valid_index = short_end_spot_curve.index[4:]
short_end_spot_curve = short_end_spot_curve.loc[valid_index]
short_end_spot_curve.head()
short_end_spot_curve.tail()
short_end_spot_curve.shape

short_end_spot_curve.shape
Out[185]: (2715, 60)

# merge these two, time index are identical
# ==============================================
combined_data = pd.concat([short_end_spot_curve, spot_curve], axis=1, join='outer')
# sort the maturity from short end to long end
combined_data.sort_index(axis=1, inplace=True)

combined_data.head()
combined_data.tail()
combined_data.shape

# deal with NaN: the most sound approach is fit the non-arbitrage NSS curve
# however, this is not currently supported in python.
# do a cubic spline instead
# ==============================================

# if more than half of the maturity points are NaN, then interpolation is likely to be unstable, so I'll remove all rows with NaNs count greater than  50
def filter_func(group):
    return group.isnull().sum(axis=1) <= 50

combined_data = combined_data.groupby(level=0).filter(filter_func)
# no. of rows down from 2715 to 2628
combined_data.shape

combined_data.shape
Out[186]: (2628, 100)


from scipy.interpolate import interp1d

# mapping points, monthly frequency, 1 mon to 25 years
maturity = pd.Series((np.arange(12 * 25) + 1) / 12)
# do the interpolation day by day
key = lambda x: x.date
by_day = combined_data.groupby(level=0)

# write out apply function
def interpolate_maturities(group):
    # transpose row vector to column vector and drops all nans
    a = group.T.dropna().reset_index()
    f = interp1d(a.iloc[:, 0], a.iloc[:, 1], kind='cubic', bounds_error=False, assume_sorted=True)
    return pd.Series(maturity.apply(f).values, index=maturity.values)

# this may take a while .... apply provides flexibility but spead is not good
cleaned_spot_curve = by_day.apply(interpolate_maturities)

# a quick look on the data
cleaned_spot_curve.iloc[[1,1000, 2000], :].T.plot(title='Cross-Maturity Yield Curve')
cleaned_spot_curve.iloc[:, [23, 59, 119]].plot(title='Time-Series')

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30898359

复制
相关文章
【笔记】《计算机图形学》(4)——光线追踪
这系列的笔记来自著名的图形学虎书《Fundamentals of Computer Graphics》,这里我为了保证与最新的技术接轨看的是英文第五版,而没有选择第二版的中文翻译版本。不过在记笔记时多少也会参考一下中文版本
ZifengHuang
2020/07/29
2.6K0
【笔记】《计算机图形学》(4)——光线追踪
CGAL:线段和多边形之间的交点?
CGAL:线段和多边形之间的交点? [英] CGAL: Intersection between a segment and a polygon? 查看:422 发布时间:2020/9/30 21
用户3519280
2023/07/06
5460
模拟试题B
1.灰度等级为256级,分辨率为2048*1024的显示器,至少需要的帧缓存容量为( )
步行者08
2018/10/09
4.3K2
爱因斯坦的光线
爱因斯坦的光线
宇相
2018/09/18
6170
爱因斯坦的光线
模拟试题A
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wpxu08/article/details/70208378
步行者08
2018/10/09
3.6K0
链表相交,找交点
力扣题目链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci
代码随想录
2021/12/22
8230
链表相交,找交点
光线追踪介绍
摘要 图像渲染就是一个这样的过程,输入一组物体,输出一个像素矩阵。把这个像素矩阵输送给显卡,显示器上就可以显示出来图像。本篇介绍下这个过程用到的算法,就是光线追踪。
一只小虾米
2022/10/25
1.1K0
光线追踪介绍
光学词汇6-系统基本概念6-主光线和边缘光线
主光线(chief ray)是从物体的一个偏离光轴的点发出,并且经过光学系统孔径光阑的中心的光线。主光线代表着从物体某一点发出的光束的中心线。
HawkWang
2023/09/01
1.8K0
光学词汇6-系统基本概念6-主光线和边缘光线
photo-distortion
Opticaldistortion=Δyy×100%TVdistortion=Δh2h×100%
为为为什么
2022/11/24
1.6K0
photo-distortion
模拟试题C
2.用编码裁剪法裁剪二维线段时,判断下列直线段采用哪种处理方法。假设直线段两个端点M、N的编码为1000和1001(按TBRL顺序)( )
步行者08
2018/10/09
2.1K0
光线传媒的爆款尴尬
突如其来的疫情,给整个国内院线电影蒙上了阴霾,也给整个电影产业链带来了持久的影响。作为电影产业链的一员,光线传媒受损严重。
刘旷
2020/08/25
4650
光线传媒的爆款尴尬
机器视觉(第3期)----图像采集之镜头原理详述
上期我们一起学习了光源相关的知识,知道了怎么选择光源,链接如下: 机器视觉(第2期)----图像采集之照明综述 镜头是一种光学设备,用于聚集光线在摄像机内部成像。镜头的作用是产生锐利的图像,以得到被测物的细节,这一期我们将一起学习使用不同镜头产生不同的成像几何,以及镜头像差是如何产生的。希望通过本期学习,我们能够掌握如何选择镜头以及像差产生的原因。 作为一个机器视觉算法人员,来介绍光学系统方面的知识,有些地方理解起来还是有些难度的,小编已经再旁边放了几摞砖,欢迎大家来拍。希望能够和大家一起交流,共同进步。
智能算法
2018/04/03
3.1K0
机器视觉(第3期)----图像采集之镜头原理详述
【笔记】《游戏编程算法与技巧》7-12
本篇是看完《游戏编程算法与技巧》后做的笔记的下半部分. 这本书可以看作是《游戏引擎架构》的入门版, 主要介绍了游戏相关的常见算法和一些基础知识, 很多知识点都在面试中会遇到, 值得一读.
ZifengHuang
2022/08/30
2.2K0
求两个链表的交点
已知链表A的头节点指针headA,链表B的头节点指针headB,两个链表相交,求两链表交点对应的节点。 [](LeetCode 160)
小飞侠xp
2018/08/29
9120
VTK:实现光照效果,从一根线到一个面
导读:很多地方需要查看光照度什么的,目前也有很多软件来处理。今天就做了一个关于光照效果的内容。从早上10点开始,到下午3点半,开始写头条号。大概就这么长时间。中午没有休息,没有吃饭。
曾高飞
2022/02/17
1.5K1
「黑悟空」实机演示炸裂登场,英伟达大秀光追技术
---- 新智元报道   编辑:Aeneas 桃子 【新智元导读】「黑悟空」时隔一年后炸裂回归,4K光追 + DLSS,让玩家大呼过瘾。 时隔一年,「黑悟空」归来再度登上热榜。 这次,除了官方发布了一段6分钟实机剧情片段,英伟达更是带来了8分钟实机试玩片段。 重磅的是,这是「黑悟空」首次支持4K  RTX ON光追+NVIDIA DLSS技术。 网友们看后瞬间热血沸腾。 首支4K光追 + DLSS 2020年,黑悟空首次曝光,惊艳全球。 到了2021年,大秀UE5的测试,那白雪纷纷的地面
新智元
2022/08/26
7620
「黑悟空」实机演示炸裂登场,英伟达大秀光追技术
链表相交,找出交点
题目链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/
代码随想录
2021/06/17
7520
Day2-球球
用户10759271
2023/09/19
1500
点击加载更多

相似问题

找到光线和多边形的交点的最快方法是什么?

41

光线-平面交点,用于确定交点的Z

10

线与球的交点

11

求光线的最远交点

11

光线不能准确地确定交点

239
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文