Ausgabe
Ich möchte nach Namen in Spalte col_one suchen, wo ich eine Liste von Namen in der Variablen list20 habe. Wenn bei der Suche der Wert von col_one mit list20 übereinstimmt, fügen Sie denselben Namen in eine neue Spalte mit dem Namen new_col ein
Meistens steht der Name vorne, z. B. ZEN, W, WICE, aber es gibt einige Namen. wieder mit einem Symbol nach dem Namen, z. B. ZEN-R, ZEN-W2, ZEN13P2302A
meine Daten
import pandas as pd
list20 = ['ZEN', 'OOP', 'WICE', 'XO', 'WP', 'K', 'WGE', 'YGG', 'W', 'YUASA', 'XPG', 'ABC', 'WHA', 'WHAUP', 'WFX', 'WINNER', 'WIIK', 'WIN', 'YONG', 'WPH', 'KCE']
data = {
"col_one": ["ZEN", "WPH", "WICE", "YONG", "K" "XO", "WIN", "WP", "WIIK", "YGG-W1", "W-W5", "WINNER", "YUASA", "WGE", "WFX", "XPG", "WHAUP", "WHA", "KCE13P2302A", "OOP-R"],
}
df = pd.DataFrame(data)
# The code you provided will give the result like the picture below. and it's not right
# or--------
df['new_col'] = df['col_one'].str.extract('('+'|'.join(list20)+')')[0]
# or--------
import re
pattern = re.compile(r"|".join(x for x in list20))
df = (df
.assign(new=lambda x: [re.findall(pattern, string)[0] for string in x.col_one])
)
# or----------
def matcher(col_one):
for i in list20:
if i in col_one:
return i
return 'na' #adjust as you see fit
df['new_col'] = df.apply(lambda x: matcher(x['col_one']), axis=1)
Das Ergebnis aus dem obigen Code und es ist nicht richtig
Erwartete Ausgabe
Lösung
Versuchen Sie zuerst, die Liste zu sortieren:
pattern = re.compile(r"|".join(x for x in sorted(list20, reverse=True, key=len)))
(df
.assign(new=lambda x: [re.findall(pattern, string)[0] for string in x.col_one])
)
Beantwortet von – William Rosenbaum
Antwort geprüft von – Jay B. (FixError Admin)