python - DataFrame 将函数应用于一列中的值以创建另一列
问题描述
我有一个包含日期和值的 csv 文件
Date, Value
2020-03-18,90.0
.
.
2020-04-10,100.0
我正在使用读取 csv 加载此文件并将函数应用于日期以将其转换为 Quantlib 日期。
pd.read_csv(file_location,header=0,float_precision='round_trip', converters = {'Date': DateList.ql_date_from_str})
这给了
Date Value
0 March 18th, 2020 90.0
.
.
20 April 10th, 2020 100.0
有没有一种快速的方法,除了拥有 Quantlib 日期外,我还可以将索引设置为加载期间的日期?
例如
Date Value
2020-03-18 March 18th, 2020 90.0
.
.
2020-04-10 April 10th, 2020 100.0
解决方案
调用时可以read_csv
使用index_col
kwarg 设置索引:
pd.read_csv(file_location,header=0,float_precision='round_trip',
converters = {'Date': DateList.ql_date_from_str},
index_col='Date')
但它会从数据框中删除该列。
相反,您可以在使用 调用后执行此read_csv
操作set_index
。确保通过,drop=False
否则该列将再次从数据框中删除:
df.set_index('Date', drop=False, inplace=True)
它可以在同一行上完成:
df = pd.read_csv(file_location,header=0,float_precision='round_trip',
converters = {'Date': DateList.ql_date_from_str}).set_index('Date', drop=False)
推荐阅读
- angular - 如何按顺序执行一组可观察对象?
- javascript - Javascript fetch() 不止一次 ping 我的 golang 休息端点?
- node.js - Nodejs mssql 全局连接
- python - 填充颜色属性颜色字符串 hsl 字符串不起作用
- java - 如何在谓词中对 FilteredList 结果进行优先级排序/排序?
- python - 从一个创建多个数据框
- tensorflow - 我可以在 C++ 中为 TensorFlow 添加复合运算符,以便该运算符可用于所有语言绑定吗?
- javascript - 轮播不会分页
- javascript - 将带有图像的画布保存到文件夹
- java - 在java中为“新手”使用显卡的最佳方法是什么