Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract first 8 characters from a string in pandas

Tags:

I have column in a dataframe and i am trying to extract 8 digits from a string. How can I do it

    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

Expected Output

Order_Date
20180504
20180514
20180514
20180514
20180514
20180516
20180516
20180516
20180516

I tried below code and it didnt work.

data['Order_Date'] = data['Shipment ID'][:8]
like image 849
Rahul rajan Avatar asked Jul 31 '18 07:07

Rahul rajan


People also ask

How do you extract the first 10 rows in pandas?

You can use df. head() to get the first N rows in Pandas DataFrame. Alternatively, you can specify a negative number within the brackets to get all the rows, excluding the last N rows.

How do you get the first 5 rows in pandas?

DataFrame. head(n) to get the first n rows of the DataFrame. It takes one optional argument n (number of rows you want to get from the start). By default n = 5, it return first 5 rows if value of n is not passed to the method.


2 Answers

You are close, need indexing with str which is apply for each value of Series:

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

For better performance if no NaNs values:

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

If omit str code filter column by position, first N values like:

print (data['Shipment ID'][:2])
0    20180504-S-20000
1    20180514-S-20537
Name: Shipment ID, dtype: object
like image 128
jezrael Avatar answered Sep 26 '22 03:09

jezrael


You can also use str.extract

Ex:

import pandas as pd

df = pd.DataFrame({'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']})
df["Order_Date"] = df["Shipment ID"].str.extract(r"(\d{8})")
print(df)

Output:

       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
like image 35
Rakesh Avatar answered Sep 22 '22 03:09

Rakesh