简体   繁体   中英

How to check pandas column names and then append to row data efficiently?

I have a dataframe with several columns, some of which have names that match the keys in a dictionary. I want to append the value of the items in the dictionary to the non null values of the column whos name matches the key in said dictionary. Hopefully that isn't too confusing.

example:

realms = {}
realms['email'] = '<email>'
realms['android'] = '<androidID>'
df = pd.DataFrame()
df['email'] = ['foo@gmail.com','',foo@yahoo.com]
df['android'] = [1234567,,55533321]

how could I could I append '<email>' to 'foo@gmail.com' and 'foo@yahoo.com' without appending to the empty string or null value too?

I'm trying to do this without using iteritems() , as I have about 200,000 records to apply this logic to.

expected output would be like 'foo@gmail.com<email>',,'foo@yahoo.com<email>'

for column in df.columns:
    df[column] = df[column].astype(str) + realms[column]
>>> df
                  email              android
0  foo@gmail.com<email>   1234567<androidID>
1  foo@yahoo.com<email>  55533321<androidID>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM