Skip to main content
 首页 » 编程设计

python之如何在不解析日期字符串的情况下调用 pandas read_csv()

2024年10月17日25Renyi-Fan

我正在处理从网上以 csv 格式下载的一些数据。原始数据如下所示。

Test Data 
"Date","T1","T2","T3","T4","T5","T6","T7","T8" 
"105/11/01","123,855","1,150,909","9.30","9.36","9.27","9.28","-0.06","60", 
"105/11/02","114,385","1,062,118","9.26","9.42","9.23","9.31","+0.03","78", 
"105/11/03","71,350","659,848","9.30","9.30","9.20","9.28","-0.03","42", 

我使用下面的代码来阅读它

import pandas as pd 
df = pd.read_csv("test.csv", skiprows=[0], usecols=[0,3,4,5]) 

我也试过用

import pandas as pd 
df = pd.read_csv("test.csv", skiprows=[0], usecols=[0,3,4,5], keep_date_col=True) 

我总是得到以下结果

           Date    T3    T4   T5 
105/11/01  9.30  9.36  9.27  NaN 
105/11/02  9.26  9.42  9.23  NaN 
105/11/03  9.30  9.30  9.20  NaN 

这就是我想要的

     Date    T3    T4    T5 
105/11/01  9.30  9.36  9.27 
105/11/02  9.26  9.42  9.23 
105/11/03  9.30  9.30  9.20 

如您所见,pandas 将日期字符串视为不是数据的一部分,并将索引向左移动一列,这导致最后一列为 NaN。

我已经阅读了 read_csv() 上的 pandas 文档并发现它可以使用 parse_dates、keep_date_col 参数解析日期,但是有什么方法可以像现在这样不解析日期吗?

请您参考如下方法:

这似乎运作良好:

import pandas as pd 
df = pd.read_csv("test.csv", skiprows=[0], usecols=[0,3,4,5], index_col=False) 
 
df 
#        Date     T3      T4      T5 
#0  105/11/01   9.30    9.36    9.27 
#1  105/11/02   9.26    9.42    9.23 
#2  105/11/03   9.30    9.30    9.20 

还有这个来自帮助文档:

index_col : int or sequence or False, default None 
    Column to use as the row labels of the DataFrame. If a sequence is given, a 
    MultiIndex is used. If you have a malformed file with delimiters at the end 
    of each line, you might consider index_col=False to force pandas to _not_ 
    use the first column as the index (row names)