如何在Python中從CSV文件的索引中刪除雙引號

2024-05-14 13:17:17 发布

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

我试图用python读取多个csv文件。原始数据的索引(或第一列)有点问题,部分csv文件如下:

NoDemande;"NoUsager";"Sens";"IdVehiculeUtilise";"NoConducteur";"NoAdresse";"Fait";"HeurePrevue"
42210000003;"42210000529";"+";"265Véh";"42210000032";"42210002932";"1";"25/07/2015 10:00:04"
42210000005;"42210001805";"+";"265Véh";"42210000032";"42210002932";"1";"25/07/2015 10:00:04"
42210000004;"42210002678";"+";"265Véh";"42210000032";"42210002932";"1";"25/07/2015 10:00:04"
42210000003;"42210000529";"—";"265Véh";"42210000032";"42210004900";"1";"25/07/2015 10:50:03"
42210000004;"42210002678";"—";"265Véh";"42210000032";"42210007072";"1";"25/07/2015 11:25:03"
42210000005;"42210001805";"—";"265Véh";"42210000032";"42210004236";"1";"25/07/2015 11:40:03"

第一个索引没有"",在读取文件之后,它看起来是:"NoDemande",而其他索引没有{},其余的列看起来很好,这使得结果看起来像(不同的行):

^{pr2}$

这会导致在接下来的移动中识别索引名称的问题。如何解决这个问题? 以下是我读取文件的代码:

import pandas as pd
import glob

pd.set_option('expand_frame_repr', False)
path = r'D:\Python27\mypfe\data_test'
allFiles = glob.glob(path + "/*.csv")
frame = pd.DataFrame()
list_ = []

for file_ in allFiles:
    #Read file
    df = pd.read_csv(file_,header=0,sep=';',dayfirst=True,encoding='utf8',
                     dtype='str')

    df['Sens'].replace(u'\u2014','-',inplace=True)

    list_.append(df)
    print"fichier lu ",file_

frame = pd.concat(list_)
print frame

Tags: 文件csvpathimporttruedfframeglob
2条回答

事实上,我被困在如何从索引中删除双引号。在更改了角度之后,我认为也许最好添加一个新列,从原始列复制值并删除它。因此,新列将具有所需的索引。 就我而言,我做到了:

frame['NoDemande'] = frame.ix[:, 0]
tl = frame.drop(frame.columns[0],axis=1)

所以我得到了一个我想要的新的。在

我认为最简单的是设置新的列名:

df.columns = ['NoDemande1'] + df.columns[1:].tolist()
print (df)
    NoDemande1     NoUsager Sens IdVehiculeUtilise  NoConducteur    NoAdresse  \
0  42210000003  42210000529    +            265Véh   42210000032  42210002932   
1  42210000005  42210001805    +            265Véh   42210000032  42210002932   
2  42210000004  42210002678    +            265Véh   42210000032  42210002932   
3  42210000003  42210000529    -           265Véh   42210000032  42210004900   
4  42210000004  42210002678    -           265Véh   42210000032  42210007072   
5  42210000005  42210001805    -           265Véh   42210000032  42210004236   

   Fait          HeurePrevue  
0     1  25/07/2015;10:00:04  
1     1  25/07/2015;10:00:04  
2     1  25/07/2015;10:00:04  
3     1  25/07/2015;10:50:03  
4     1  25/07/2015;11:25:03  
5     1  25/07/2015;11:40:03  

另一个解决方案是来自列名的^{}"

^{pr2}$

相关问题 更多 >

    热门问题