mardi 3 octobre 2017

How can i create a ruleset to assign values to specific columns, based on searching substrings, in Pandas?

I am a complete newbie to Python (and Pandas library) and need to recreate some SQL code in it.

My task is quite simple of the face of it, I have a few columns, and i need to search them for specific strings, and if they exist then a value is placed in category columns.

e.g.

import pandas as pd

phone_ds= [('IPHONE_3UK_CONTRACT', 968), ('IPHONE_O2_SIMONLY', 155), ('ANDROID_3UK_PAYG', 77), , ('ANDROID_VODAF_CONTRACT', 973)]

a = pd.DataFrame(data=phone_ds, columns=['Names', 'qty'])

def f(a):
    if a['Names'].str.contains('3UK'):
        company = 'Three'
    if a['Names'].str.contains('iPhone'):
        OS = 'iOS'
.
.
.
etc

Is there a better (more efficient) way than listing if statements?

How would i go about adding the results into new columns?

Thanks

Aucun commentaire:

Enregistrer un commentaire