简体   繁体   中英

Extract text after period “.” from values in a column in Pandas Dataframes

I have a column in a dataframe as follows:

| Category |
------------
| B5050.88
| 5051.90
| B5050.97Q
| 5051.23B
| 5051.78E
| B5050.11
| 5051.09
| Z5052

I want to extract the text after the period. For example, from B5050.88, I want only "88"; from 5051.78E, I want only "78E"; for Z50502, it would be nothing as there's no period.

Expected output:

| Category | Digits |
---------------------
| B5050.88 | 88  |
| 5051.90  | 90  |
| B5050.97Q| 97Q |
| 5051.23B | 23B |
| 5051.78E | 78E |
| B5050.11 | 11  |
| 5051.09  | 09  |
| Z5052    | -   |

I tried using this

df['Digits'] = df.Category.str.extract('.(.*)')

But I'm not getting the right answer. Using the above, for B5050.88, I'm getting the same B5050.88; for 5051.09, I'm getting NaN. Basically NaN if there's no text.

You can do

splits = [str(p).split(".") for p in df["Category"]]
df["Digits"] = [p[1] if len(p)>1 else "-" for p in splits]

ie


df = pd.DataFrame({"Category":["5050.88","5051.90","B5050.97","5051.23B","5051.78E",
"B5050.11","5051.09","Z5052"]})

#df

#   Category
# 0 5050.88
# 1 5051.90
# 2 B5050.97
# 3 5051.23B
# 4 5051.78E
# 5 B5050.11
# 6 5051.09
# 7 Z5052

splits = [str(p).split(".") for p in df["Category"]]
splits

# [['5050', '88'],
 # ['5051', '90'],
 # ['B5050', '97'],
 # ['5051', '23B'],
 # ['5051', '78E'],
 # ['B5050', '11'],
 # ['5051', '09'],
 # ['Z5052']]

df["Digits"] = [p[1] if len(p)>1 else "-" for p in splits]
df

# Category  Digits
# 0 5050.88     88
# 1 5051.90     90
# 2 B5050.97    97
# 3 5051.23B    23B
# 4 5051.78E    78E
# 5 B5050.11    11
# 6 5051.09     09
# 7 Z5052        -

not so pretty but it works

EDIT:

Added the "-" instead of NaN and the code snippet

Another way

df.Category.str.split('[\.]').str[1]

0     88
1     90
2    97Q
3    23B
4    78E
5     11
6     09
7    NaN

Alternatively

df.Category.str.extract('((?<=[.])(\w+))')

You need to escape your first . and do fillna :

df["Digits"] = df["Category"].astype(str).str.extract("\.(.*)").fillna("-")
print(df)

Output:

    Category Digits
0   B5050.88     88
1    5051.90     90
2  B5050.97Q    97Q
3   5051.23B    23B
4   5051.78E    78E
5   B5050.11     11
6    5051.09     09
7      Z5052      -

try out below :

df['Category'].apply(lambda x : x.split(".")[-1] if "." in list(x) else "-")

check below code在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM