首页 > 解决方案 > 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

标签: pythonpandasdataframe

解决方案


调用时可以read_csv使用index_colkwarg 设置索引:

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)

推荐阅读