gpt4 book ai didi

python - 根据列表替换列中的项目

转载 作者:太空宇宙 更新时间:2023-11-03 14:12:05 27 4
gpt4 key购买 nike

我有一个像这样的数据框:

Date        Value
19990506 0.6
19990506 0.8
19990607 1.2
20000802 0.4

我也有两个这样的列表:

list1 = ['19990506', '19990607', '20000802']
list2 = ['1999201', '1999232', '2000252']

list1 中的项目与 Date 列中的值一致,我想用 list2 中的项目替换它们。所以在 Date 中,19990506 被替换为 1999201 并且 19990607 被替换为 1999232。我想我需要压缩我的列表来做到这一点,但在那之后我就不知道最好的方法了。我展示的是一个非常简化的数据框,所以简单地使用 .replace 对我来说效率不高。我想要的输出是这样的:

Date      Value
1999201 0.6
1999201 0.8
1999232 1.2
2000252 0.4

最佳答案

如果您创建一个从 list1 映射到 list2 的字典,那么您可以使用 Series.map:

df = pd.read_clipboard()

list1 = ['19990506', '19990607', '20000802']
list2 = ['1999201', '1999232', '2000252']

# When I read in your data I get ints in the Date column
# so I need ints in the replacement map, if you have
# strings then remove the int() conversions
replacement_map = {int(i1): int(i2) for i1, i2 in zip(list1, list2)}
df['Date'] = df['Date'].map(replacement_map)
df
Out[13]:
Date Value
0 1999201 0.6
1 1999201 0.8
2 1999232 1.2
3 2000252 0.4

关于python - 根据列表替换列中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36707741/

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