DataFrame将函数应用于一列中的值以创建另一列

时间:2020-02-06 12:40:55

标签: python pandas 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

2 个答案:

答案 0 :(得分:1)

您可以使用read_csv kwarg来调用index_col时设置索引:

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)

答案 1 :(得分:1)

from selenium import webdriver driver = webdriver.Chrome('/home/ava/Webautomator/chromedriver') #filepath of the driver driver.get("www.google.com") 之后,复制列:

Traceback (most recent call last): File "webautomator2.py", line 4, in <module> driver.get("www.google.com") File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 333, in get self.execute(Command.GET, {'url': url}) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidArgumentException: Message: invalid argument (Session info: chrome=80.0.3987.87)

然后设置索引:

pd.read_csv

然后仅将列转换为Quantlib日期。

NB:DeepSpace的答案将为您提供带有QuantLib日期的索引