English 中文(简体)
由任何划界和定购物价值[复制]
原标题:Split col by any delimiter and Uppercase values [duplicate]

页: 1

Below, I have a df with Value containing various combinations. I want to split the col into two individuals columns, whereby, everything before the last - and uppercase letters.

页: 1

df = pd.DataFrame({
    Value : [ Juan-Diva - HOLLS ,  Carlos - George - ESTE BAN - BOM ,  Javier Plain - Hotham Ham - ALPINE ,  Yul - KONJ KOL MON ],
   })

备选办法 1 P-4, 1 P-3, 1 FS, 1 NS

df[[ First ,  l ]] = df[ Value ].str.split(  -  , n=1, expand=True)

df[ Last ] = df[ Value ].str.split( -  ).str[-1]

备选案文2

# Regular expression pattern
pattern = r ^(.*) - ([A-Zs]+)$ 

# Extract groups into two new columns
df[[ First ,  Last ]] = df[ Value ].str.extract(pattern)

option 3)

df[["First", "Last"]] = df["Value"].str.rsplit(" - ", n=1, expand=True)

None of these options return the intended output.

预期产出:

                       First            Last
0                  Juan-Diva           HOLLS
1            Carlos - George  ESTE BAN - BOM
2  Javier Plain - Hotham Ham          ALPINE
3                        Yul    KONJ KOL MON
问题回答

Using Pandas built-in vectorized string operations

import pandas as pd

df = pd.DataFrame({
    Value : [ Juan-Diva - HOLLS ,  Carlos - George - ESTE BAN ,  Javier Plain - Hotham Ham - ALPINE ,  Yul - KONJ KOL MON ],
})

# Regular expression pattern
pattern = r ^(.*) - ([A-Zs]+)$ 

# Extract groups into two new columns
df[[ First ,  Last ]] = df[ Value ].str.extract(pattern)

# Display the DataFrame
print(df)

产出:

                                Value                      First          Last
0                   Juan-Diva - HOLLS                  Juan-Diva         HOLLS
1          Carlos - George - ESTE BAN            Carlos - George      ESTE BAN
2  Javier Plain - Hotham Ham - ALPINE  Javier Plain - Hotham Ham        ALPINE
3                  Yul - KONJ KOL MON                        Yul  KONJ KOL MON

在这项法典中,经常表述为<代码>r ^(*)-([A-Zs]+]$>。 模式涉及两个群体:

  1. (.*) captures everything before the last " - ".
  2. ([A-Zs]+)$ captures the last uppercase string following " - ".

<代码>.str.extract(>> 方法之后,根据这些捕获组建立了两个栏目的数据框架。


www.un.org/Depts/DGACM/index_spanish.htm 替代方法:re

import pandas as pd
import re

df = pd.DataFrame({
     Value : [ Juan-Diva - HOLLS ,  Carlos - George - ESTE BAN ,  Javier Plain - Hotham Ham - ALPINE ,  Yul - KONJ KOL MON ],
})

# Function to split the string
def split_value(s):
    # Find the last occurrence of   -   followed by uppercase letters
    match = re.search(r (.*) - ([A-Zs]+)$ , s)
    if match:
        return match.group(1), match.group(2)
    else:
        return s, None

# Apply the function to each row in  Value  column
df[[ First ,  Last ]] = df[ Value ].apply(lambda x: split_value(x)).tolist()

print(df)

产出:

                                Value                      First          Last
0                   Juan-Diva - HOLLS                  Juan-Diva         HOLLS
1          Carlos - George - ESTE BAN            Carlos - George      ESTE BAN
2  Javier Plain - Hotham Ham - ALPINE  Javier Plain - Hotham Ham        ALPINE
3                  Yul - KONJ KOL MON                        Yul  KONJ KOL MON

使用<代码>re.search的Im,根据具体模式找到对应办法。 www.un.org/chinese/ga/president 如果发现对应数据,则该功能将分机的两个部分;否则,该功能将回到最后一栏的原座和<代码>None。 然后将结果转化为清单,并分配给第一栏和最后一栏。

缩略语

df[["First", "Last"]] = df["Value"].str.rsplit(" - ", n=1, expand=True)
print(df)

印刷:

                                Value                      First          Last
0                   Juan-Diva - HOLLS                  Juan-Diva         HOLLS
1          Carlos - George - ESTE BAN            Carlos - George      ESTE BAN
2  Javier Plain - Hotham Ham - ALPINE  Javier Plain - Hotham Ham        ALPINE
3                  Yul - KONJ KOL MON                        Yul  KONJ KOL MON




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签