calling a dataframe column name in the parameters of a function

Viewed 258

I have a dataframe with 8 columns that i would like to run below code (i tested it works on a single column) as a function to map/apply over all 8 columns. click here for sample of dataframe

all_adj_noun = []
for i in range(len(bigram_df)):
    if len([bigram_df['adj_noun'][i]]) >= 1:
        for j in range(len(bigram_df['adj_noun'][i])):
            all_adj_noun.append(bigram_df['adj_noun'][i][j])

However, when i tried to define function the code returns an empty list when it is not empty.

def combine_bigrams(df_name, col_name):
    all_bigrams = []
    for i in range(len(df_name)):
        if len([df_name[col_name][i]]) >= 1:
            for j in range(len(df_name[col_name][i])):
                return all_bigrams.append(df_name[col_name][i][j])

I call the function by

combine_bigrams(bigram_df, 'adj_noun')

May I know is there anything that I may be doing wrong here?

1 Answers

The problem is that you are returning the result of .append, which is None

However, there is a better (and faster) way to do this. To return a list with all the values present in the columns, you can leverage Series.agg:

col_name = 'adj_noun'
all_bigrams = bigram_df[col_name].agg(sum)
Related