有“”行时如何分隔CSV文件?

2024-04-25 06:49:53 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在一个CSV文件中读取如下内容时:

To, ,New York ,Norfolk ,Charleston ,Savannah 

Le Havre (Fri), ,15 ,18 ,22 ,24 

Rotterdam (Sun) ,"",13 ,16 ,20 ,22 

Hamburg (Thu) ,"",11 ,14 ,18 ,20 

Southampton (Fri) , "" ,8 ,11 ,15 ,17

使用熊猫,如下所示:

duration_route1 =  pd.read_csv(file_name, sep = ',')

我得到以下结果(我使用Sublime文本运行Python代码):

enter image description here

您可以看到,当存在""时,它不会分隔字符串。为什么它不这样做?你知道吗


Tags: 文件csvtole内容newsunyork
3条回答

您需要quoting=csv.QUOTE_NONE,因为file中有quoting

df = pd.read_csv('TAT_AX1_westbound_style3.csv', quoting=csv.QUOTE_NONE)
print (df)
                    To          New York   Norfolk   Charleston  Savannah 
0       Le Havre (Fri)                 15        18           22       24 
1    "Rotterdam (Sun)     """"         13        16           20      22 "
2      "Hamburg (Thu)     """"         11        14           18      20 "
3  "Southampton (Fri)    """"           8        11           15      17 "
#remove first column 
df = df.drop(df.columns[0], axis=1)
#remove all " values to empty string, convert to int
df = df.replace({'"':''}, regex=True).astype(int)
print (df)
                     New York   Norfolk   Charleston   Savannah 
To                                                              
Le Havre (Fri)              15        18           22         24
"Rotterdam (Sun)            13        16           20         22
"Hamburg (Thu)              11        14           18         20
"Southampton (Fri)           8        11           15         17     15       17

只需在python中使用csv库, 导入并使用。你知道吗

import csv

file_obj = #your_file_object_read_mode
rows = file_obj.readlines()

for raw in csv.DictReader(rows, delimiter=","):
    print(raw) # the raw will be a dictionary and you can use it well for any need. 

每一个生料看起来都像

{'number3': '88', 'number2': '22', 'name': 'vipul', 'number1': '23'}

我想这解决了你的问题,试试看。你知道吗

从您提供的示例来看,很明显问题出在数据集上,pandas工作正常。你知道吗

只有第一行被正确分隔,第二行全部在一列中;作为单个字符串(注意")。如果我将,替换为|,您的问题会变得更清楚:

To                                        | |New York |Norfolk |Charleston |Savannah 
Le Havre (Fri)                            | |15       |18      |22         |24 
"Rotterdam (Sun) ,"""",13 ,16 ,20 ,22 "   | 
"Hamburg (Thu) ,"""",11 ,14 ,18 ,20 "     |
"Southampton (Fri) , """" ,8 ,11 ,15 ,17 "|

现在您必须手动拆分第二行以创建正确的数据集。你知道吗

>>> with open('sample2.txt') as f:
...    headers = next(f).split(',')
...    rows = [i.split(',') for i in f]
...
>>> rows = [list(map(str.strip, list(map(lambda x: x.replace('"', ''), i)))) for i in rows]
>>> pd.DataFrame(rows, columns=headers)
                  To   New York Norfolk Charleston Savannah
0     Le Havre (Fri)         15      18         22       24
1    Rotterdam (Sun)         13      16         20       22
2      Hamburg (Thu)         11      14         18       20
3  Southampton (Fri)          8      11         15       17

相关问题 更多 >