无法从html页面正确读取和格式化日期列

时间:2019-05-03 16:02:34

标签: python html dataframe

以正确的格式解析日期列时遇到问题。我正在使用pd.read_html从HTML页面读取数据。我正在读取的数据如下所示:

picture: data source

URL放在数据中。

我正在阅读以下内容:

list = pd.read_html("https://www.onvista.de/onvista/times+sales/popup/historische-kurse/?notationId=253929&dateStart=30.04.2018&interval=M3&assetName=Apple&exchange=Nasdaq", header=0, parse_dates=[0],  decimal=',', thousands='.')

当我以某种方式打印时,某些日期会逐月切换。例如,第0行看起来不错,但对于第1-9行,则切换了月份和日期。第10和11行再次看起来不错。它会在前几个月的整个月份内发生。

picture: output with parsing date

我试图在不将date列解析为datetime的情况下加载数据,因此我可以根据需要设置列的格式,但是如果我打印数据框,则该列将丢失单独的.

picture: output without parsing date

有人知道我如何正确读取数据吗?

1 个答案:

答案 0 :(得分:0)

不确定为什么parse_dates无法正常工作,但是您可以使用datetime和熊猫的DataFrame apply方法来转换日期。一项注意事项-由于日期中的日期缺少零填充,因此出现了一些复杂的问题:

import pandas as pd
from datetime import datetime
lista = pd.read_html("https://www.onvista.de/onvista/times+sales/popup/historische-kurse/?notationId=253929&dateStart=30.04.2018&interval=M3&assetName=Apple&exchange=Nasdaq", header=0,  decimal=',', thousands='.')
df = lista[0]
df['Datum'] = df.apply(lambda x: datetime.strptime(x['Datum'].astype(str)[:-2], '%d%m%Y')
                       if len(x['Datum'].astype(str)[:-2]) == 8 else 
                       datetime.strptime('0' + x['Datum'].astype(str)[:-2], '%d%m%Y'), axis=1)

这将返回:

Datum   Eröffnung   Hoch    Tief    Schluss Volumen
0   2018-04-30  162.19  167.26  161.840 165.26  42427424
1   2018-05-01  166.35  169.20  165.270 169.10  53569376
2   2018-05-02  175.25  177.75  173.800 176.57  66539371
3   2018-05-03  175.68  177.50  174.441 176.89  34068180
4   2018-05-04  178.17  184.25  178.170 183.83  56201317
相关问题