gpt4 book ai didi

python-3.x - 如何从 Pandas 字符串中提取前8个字符

转载 作者:行者123 更新时间:2023-12-01 03:03:04 24 4
gpt4 key购买 nike

我在数据框中有列,我正尝试从字符串中提取8位数字。我该怎么做

    Input
Shipment ID
20180504-S-20000
20180514-S-20537
20180514-S-20541
20180514-S-20644
20180514-S-20644
20180516-S-20009
20180516-S-20009
20180516-S-20009
20180516-S-20009

预期输出
Order_Date
20180504
20180514
20180514
20180514
20180514
20180516
20180516
20180516
20180516

我尝试下面的代码,它没有工作。
data['Order_Date'] = data['Shipment ID'][:8]

最佳答案

您接近了,需要使用str进行索引,该索引适用于Serie的每个值:

data['Order_Date'] = data['Shipment ID'].str[:8]

如果没有 NaN的值,则为获得更好的性能:
data['Order_Date'] = [x[:8] for x in data['Shipment ID']]
print (data)
Shipment ID Order_Date
0 20180504-S-20000 20180504
1 20180514-S-20537 20180514
2 20180514-S-20541 20180514
3 20180514-S-20644 20180514
4 20180514-S-20644 20180514
5 20180516-S-20009 20180516
6 20180516-S-20009 20180516
7 20180516-S-20009 20180516
8 20180516-S-20009 20180516

如果按位置省略 str代码过滤器列,则前N个值如下:
print (data['Shipment ID'][:2])
0 20180504-S-20000
1 20180514-S-20537
Name: Shipment ID, dtype: object

关于python-3.x - 如何从 Pandas 字符串中提取前8个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51607400/

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