【问题标题】:Split Columns with ' ' and Drop One of the New Columns使用 ' ' 拆分列并删除其中一个新列
【发布时间】:2016-07-12 15:11:28
【问题描述】:

我有一个这样的 csv 文件:

"NoDemande;"NoUsager";"Sens";"IdVehicule";"NoConducteur";"NoAdresse";"Fait";"aPaye";"MethodePaiement";"ArgentPercu";"HeurePrevue";"HeureDebutTrajet";"HeureArriveeSurSite";"HeureEffective"
    0003;"2021";"+";"157Véh";"0002";"5712";"1";"";"";"";"07/07/2015 06:30:04";"07/07/2015 06:15:48";"07/07/2015 06:32:14";"07/07/2015 06:32:23"
    0265;"0496";"+";"161Véh";"0035";"04075";"1";"";"";"";"07/07/2015 06:35:04";"07/07/2015 05:09:55";"07/07/2015 06:36:18";"07/07/2015 06:36:27"
    0004;"2208";"+";"157Véh";"0002";"5713";"1";"";"";"";"07/07/2015 06:45:04";"07/07/2015 06:32:23";"07/07/2015 06:40:05";"07/07/2015 06:40:10"

我想做什么:

  1. 拆分一些列,将包含“日期”和“时间”的列分成两列。
  2. 仅保存一列“日期”并删除其他列。

我试过这样:

#coding=latin-1

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:
    df = pd.read_csv(file_,index_col=None,header=0,sep=';')
    s1 = df['HeurePrevue'].apply(lambda x: x.split(' '))
    df['Date'] = s1.apply(lambda x: x[0])
    df['HeurePrevue'] = s1.apply(lambda x: x[1])

frame = pd.concat(list_)

print frame

它适用于一列,但是当我想对第二列执行相同操作时,它不再有效。我应该怎么做才能使它与我的所有列一起工作,同时保持其他列保持不变?

【问题讨论】:

  • 我看不到您试图仅将后续列拆分为第一列
  • 我只成功分割了第一个...

标签: python pandas time split


【解决方案1】:
import io
import pandas as pd

raw_df = io.StringIO("""\
HeurePrevue           HeureDebutTrajet    HeureArriveeSurSite     HeureEffective
06/07/2015 05:30:04  06/07/2015 16:54:31  06/07/2015 16:54:35  06/07/2015 16:54:38
06/07/2015 06:10:04  06/07/2015 05:38:39  06/07/2015 06:29:51  06/07/2015 06:30:06
06/07/2015 06:10:04  06/07/2015 05:38:39  06/07/2015 06:29:51  06/07/2015 06:30:06
""")
df = pd.read_csv(raw_df, index_col=None, skiprows=1, header=None,
                 delim_whitespace=True)

df = df[[0, 1, 3, 5, 7]]
df.columns = ['Date', 'HeurePrevue', 'HeureDebutTrajet', 'HeureArriveeSurSite',
              'HeureEffective']

输出:

         Date HeurePrevue HeureDebutTrajet HeureArriveeSurSite HeureEffective
0  06/07/2015    05:30:04         16:54:31            16:54:35       16:54:38
1  06/07/2015    06:10:04         05:38:39            06:29:51       06:30:06
2  06/07/2015    06:10:04         05:38:39            06:29:51       06:30:06

【讨论】:

  • 当我想从文件中获取我的列时它不起作用,我不能在StringIO 中使用path
  • StringIO 部分很简单,因此代码可以通过简单的复制粘贴评估进行测试。删除raw_df = ... 行,并将下一行中的raw_df 更改为您的csv 文件的名称。
  • @ch36r5s 如果这个或任何答案已经解决了您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
猜你喜欢
  • 1970-01-01
  • 2021-02-19
  • 2021-06-07
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
  • 2010-12-09
相关资源
最近更新 更多