user5826447
user5826447

Reputation: 367

plug all values from a pandas dataframe column into a function

I have a df with a column of strings and a function that takes in a string. I would like to go through the df plugging in the values in that column without typing it, what is the best way to go about this? I looked into apply but it didn't seem applicable in this situation.

Edit:

df = A B     C
     1 2 "cheese"
     2 4 "spiders"

def samplefunc(item):
    print('i hate ' + item)

Upvotes: 1

Views: 119

Answers (2)

jezrael
jezrael

Reputation: 862511

I think you need Series.apply:

def samplefunc(item):
    print('i hate ' + item)

df.C.apply(samplefunc)
i hate cheese
i hate spiders

Upvotes: 3

piRSquared
piRSquared

Reputation: 294218

df = pd.DataFrame([
        [1, 2, 'cheese'],
        [2, 4, 'spiders']
    ], columns=list('ABC'))

df.loc[:, 'C'] = df.C.apply('I hate {}'.format)

df

enter image description here

Upvotes: 3

Related Questions