gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:43:51 25 4
gpt4 key购买 nike

例如,我想将 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

最佳答案

从系列开始,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

关于python - 替换 pandas 系列中的值,其中要替换的元素包含要替换的元素的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50541508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com