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

2024-04-27 04:31:29 发布

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

例如,我想用2014替换2/8/2014 0:00,然后用2015替换1/29/2015 0:00。你知道吗

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条回答

试试这个:

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

这只是一个虚拟序列

只需对series使用apply函数,然后将lambda添加到参数中,然后对其进行索引

从系列开始,ser

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

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

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

如果你想按年份分组,你可以按索引分组:

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

相关问题 更多 >