I have a pandas data frame where, there is a string column A. I want to match for specific key words in the list below and create a new column.
[Android, iOS, Windows, Linux, MacOS].
If there is no match from the above list, then the new column value is 'Other'.
Column_A | New_Column |
---|---|
Android10 | Android |
iPhoneiOS 13.5.1 | iOS |
SamsungAndroid 9 | Android |
Windows 10 | Windows |
iPhoneiOS 13.7 | iOS |
iOS 14.2 | iOS |
iOS 13.6 | iOS |
iOS 13.6.1 | iOS |
iOS 14.1 | iOS |
iOS 13.4.1 | iOS |
iOS 14.0.1 | iOS |
HTCAndroid 8.1.0 | Android |
Android 8.0.0 | Android |
iOS 14.0 | iOS |
Chrome OS | Other |
Windows 7 | Windows |
Mac OS X 10.15.4 | MacOS |
You can try following code:
Creating dummy dataframe and list of words to match:
terms = ['Android', 'iOS','Windows']
x = pd.DataFrame({'Col1':['iPhoneiOS 13.5.1','Android10','SamsungAndroid 9','Windows 10','iPhoneiOS 13.7','iOS 14.2','Test','',np.nan]})
Helper function to find strings:
def find_str(x):
for i in terms:
if i.lower() in x.lower():
return i
else:
return 'Others'
x['Match'] = x['Col1'].astype(str).apply(lambda x: 'Others' if x is None else find_str(x))
print(x)
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.