1 year ago

#386773

test-img

Aggelos Tamvakis

eIteration over pandas dataframe index

I want to iterate over a list (tokens), and if a specific token is contained within the list tokens, then I want to assign a value on a pandas dataframe column. My task can be seen in the following lines of code:

def set_party(tokens):
    democrat_kwrds = ['clinton', ... etc]
    republican_kwrds = ['trump', ... etc]
    for i, tweet in enumerate(tokens):
        dem = False
        rep = False
        print(tweet)
        for word in tweet:
            if word in democrat_kwrds:
                dem = True
            elif word in republican_kwrds:
                rep = True
            print(word)
    if dem and not rep:
        df_cleaned.loc[i,'party'] = 'dem'
    elif not dem and rep:
        df_cleaned.loc[i,'party'] = 'rep'
    else:
        df_cleaned.loc[i,'party'] = 'Nothing'

my problem is that I get nothing in the column('party') of df_cleaned at the end of iteration. I removed .loc[i] and run the code, then the function assigns 'Nothing' to the 'party' column of df_cleaned which is the correct answer considering the first row of the list tokens. So I assume the function works ok and it is an indexing problem. Does anybody have any ideas?

tokens is a list of strings, here an example:

print(tokens[0]):

['think', 'ashamed', 'stand', 'pervert', 'husband', 'like']

pandas

loops

for-loop

indexing

0 Answers

Your Answer

Accepted video resources