如何使用pandas从csv文件中读取字段的一部分?

时间:2015-06-12 11:16:10

标签: python pandas

我有一个csv文件 以下字段

YEAR QUARTER   MONTH      WEEK           DAY
2015  20151   201501      201501W1     20150101
2015  20151   201501      201501W1     20150102
2015  20151   201501      201501W1     20150103
2015  20151   201501      201501W1     20150104
2015  20151   201501      201501W1     20150105
....

如何仅从DAY字段中获取最后两位数字,即01,02,03,04 ...等,以便我可以根据当天替换剩余的字段。请建议我们还有其他办法吗?

1 个答案:

答案 0 :(得分:1)

import pandas as pd
import io

data = """
YEAR,QUARTER,MONTH,WEEK,DAY
2015,20151,201501,201501W1,20150101
2015,20151,201501,201501W1,20150102
2015,20151,201501,201501W1,20150103
2015,20151,201501,201501W1,20150104
2015,20151,201501,201501W1,20150105
"""

df = pd.read_csv(io.StringIO(data), dtype=object)

df.DAY.str[-2:]

为您提供了一系列DAY列的最后两位数字:

0    01
1    02
2    03
3    04
4    05
Name: DAY, dtype: object