I have a Panda Series and a Dataframe column, containing special characters, spaces and have extra characters at the end (one column has singular form of fruits, the other plural). You can see that in the first element, ä is transcribed as a in apple, but in Banänas it is transcribed as bananaes.
a = pd.Series(['Äpple', 'Orange & Pear', 'Banänas', 'Octopi', 'Wine'])
df = {
"fruits": ['apple','orange-something-pear', 'bananaes', 'octopus', 'kiwi'],
"amounts": [100, 200, 300, 400, 500]
}
I need a result, which looks the following:
df = {
"fruits": ['apple','orange-something-pear', 'octopus', 'bananaes', 'kiwi'],
"amounts": [100, 200, 300, 400, 500],
"title": ['Äpples', 'Orange & Pear', 'Banänas', 'Octopi', NaN]
}
So far, I've thought of the following:
- make the Series
alowercase and replace special characters with regex using a dictionary - match the regex column with
df['fruits']
Code that I have:
import pandas as pd
# data
s = pd.Series(['Äpple', 'Orange & Pear', 'Banänas', 'Octopi', 'Wine'])
df = {
"fruits": ['apple','orange-something-pear', 'bananaes', 'octopus', 'kiwi'],
"amounts": [100, 200, 300, 400, 500]
}
#lowercase
s = s.str.lower()
# dictionary for replacement
rep_dict = {"ö":"(.{1,2})", "ä":'(.{1,2})', "ü":'(.{1,2})', " & ":'-(.?)-'}
# replace
s2 = s.replace(rep_dict)
# make into a dictionary
s_dict = dict(zip(s, s2))
# map/match the dict to df
(pd.concat((df['fruits'].str.match(k) for k in s_dict), axis=1, ignore_index = True)
.dot(pd.Series(d for k, d in s_dict.items()))
)
The match does not work, though (followed this question: How to use map with a dictionary having regular expression keys?)
Also I'm not sure, how to take into account only the beginning of the string, due to the plural suffixes at the end.
I'm super grateful for any help, I hope the question is fine how it is, otherwise I'm happy to split it into subquestions.