gpt4 book ai didi

python - 将 int64 Pandas 列一分为二

转载 作者:太空狗 更新时间:2023-10-30 01:40:18 24 4
gpt4 key购买 nike

我得到了一个数据集,该数据集的日期为整数,格式为 52019,表示 2019 年 5 月。我已将其放入 Pandas DataFrame 中,我需要将该日期格式提取到月列和年列中,但我无法弄清楚如何为 int64 数据类型执行此操作或如何处理两位数的月份。所以我想采取类似的东西

ID    Date
1 22019
2 32019
3 52019
5 102019

让它变成

ID    Month    Year
1 2 2019
2 3 2019
3 5 2019
5 10 2019

我该怎么办?

最佳答案

divmod

df['Month'], df['Year'] = np.divmod(df.Date, 10000)

df

ID Date Month Year
0 1 22019 2 2019
1 2 32019 3 2019
2 3 52019 5 2019
3 5 102019 10 2019

不使用 assign 改变原始数据帧

df.assign(**dict(zip(['Month', 'Year'], np.divmod(df.Date, 10000))))

ID Date Month Year
0 1 22019 2 2019
1 2 32019 3 2019
2 3 52019 5 2019
3 5 102019 10 2019

关于python - 将 int64 Pandas 列一分为二,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56241804/

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