替换pandas系列中的值,其中要替换的元素包含要替换它的元素的一部分

时间:2018-05-26 09:57:46

标签: python python-3.x pandas replace

例如,我想将2/8/2014 0:00替换为2014,将1/29/2015 0:00替换为2015此后。

2014               180657
2015               153837
2014                72395
2012                69708
2013                61364
2015                54117
2013                 3313
2012                 1076
2/8/2014 0:00           2
7/3/2014 0:00           2
1/29/2015 0:00          2
9/1/2014 0:00           2
11/22/2014 0:00         2
10/16/2014 0:00         2

2 个答案:

答案 0 :(得分:4)

从系列开始,2014 180657 2015 153837 2014 72395 2012 69708 2013 61364 2015 54117 2013 3313 2012 1076 2/8/2014 0:00 2 7/3/2014 0:00 2 1/29/2015 0:00 2 9/1/2014 0:00 2 11/22/2014 0:00 2 10/16/2014 0:00 2 dtype: int64

ser.index = pd.to_datetime(ser.index, errors='coerce').year
ser

2014    180657
2015    153837
2014     72395
2012     69708
2013     61364
2015     54117
2013      3313
2012      1076
2014         2
2014         2
2015         2
2014         2
2014         2
2014         2
dtype: int64

您可以将索引转换为日期时间并提取年份:

ser = ser[ser.index.notnull()]
ser.index = ser.index.astype('int')

如果这引入了NaN,您可以通过

消除它们
ser.groupby(level=0).sum()
Out: 
2012     70784
2013     64677
2014    253062
2015    207956
dtype: int64

如果您想按年份对此进行分组,您可以对索引进行分组:

background-size

答案 1 :(得分:0)

试试这个:

s = pd.Series(['2017','2/3/2018 6:45'])
s = s.apply(lambda x: x.split()[0][-4:])
print(s)

输出:

0    2017
1    2018
dtype: object

这只是一个虚拟系列

只需使用系列的apply函数,然后在参数中添加lambda,然后将其编入索引