如何使用新列拆分和替换数据框中的列

时间:2018-01-18 19:04:46

标签: python pandas

我有一个Dataframe如下:

import pandas as pd
dic = {'title':['A', 'B', 'C'], 'Date':['1/1/2010 to 2/1/2010', '3/1/2010 to 
                 4/1/2010', '5/1/2010 to 6/1/2010'], 'Value':[1.0, 2.2, 3.3]}
df = pd.DataFrame(dic)

DataFrame如下:

df
   title                  Date  Value 
0      A  1/1/2010 to 2/1/2010    1.0 
1      B  3/1/2010 to 4/1/2010    2.2 
2      C  5/1/2010 to 6/1/2010    3.3 

我想将整个Date列拆分为Start_DateEnd_Date,如下所示:

   title  Start_Date  End_Date  Value 
0      A    1/1/2010  2/1/2010    1.0 
1      B    3/1/2010  4/1/2010    2.2 
2      C    5/1/2010  6/1/2010    3.3 

知道怎么做吗?

3 个答案:

答案 0 :(得分:3)

使用str split

df[['StartDate','EndDate']]=df.Date.str.split(' to ',expand=True)
df
Out[36]: 
                   Date  Value title StartDate   EndDate
0  1/1/2010 to 2/1/2010    1.0     A  1/1/2010  2/1/2010
1  3/1/2010 to 4/1/2010    2.2     B  3/1/2010  4/1/2010
2  5/1/2010 to 6/1/2010    3.3     C  5/1/2010  6/1/2010

答案 1 :(得分:0)

我使用列表推导来分割列。但是现在我看到这个答案将失败,我们在Date字段中有不同数量的字符。拆分'到'比如上面的答案更好。

df['Start Date'] = [d[0:9] for d in df.Date]
df['End Date'] = [d[11:] for d in df.Date]

    Date                    Value title Start Date  End Date
0   1/1/2010 to 2/1/2010    1.0     A   1/1/2010    2/1/2010
1   3/1/2010 to 4/1/2010    2.2     B   3/1/2010    4/1/2010
2   5/1/2010 to 6/1/2010    3.3     C   5/1/2010    6/1/2010

答案 2 :(得分:0)

df[['start','end']] = pd.DataFrame(df.Date.str.split('to ').tolist())

您必须在to

上拆分日期列