简体   繁体   中英

How do I apply this string length function to a column in my dataframe?

I have written a function that returns the length of a string,

def string_length():
string = input("Please enter a string: ")
"""This prompts the user to enter a string"""
return(len(string))

I have a dataset called film which has a column titled Phrase . I want to add a new column to my dataset which applies my function to the Phrase column and inputs the string length for each value in the phrase.

I tried using the following code:

film['Phrase length']=film['Phrase'].apply(string_length)

However, this returns an error:

TypeError: string_length() takes 0 positional arguments but 1 was given

What do I need to do to fix this code?

I'm sure I'm missing something very silly but I'm still quite new to python!

The function prompts the user for some input. This won't work if you apply it to a dataframe. You can however apply the built-in len() function:

film['Phrase length'] = film.Phrase.apply(len)

If I understand your question correctly then you must be looking for this:

def string_length(str):
    x = len(str)
    return x

df['Phrase length'] = df['Phrase'].apply(lambda x: string_length(x))

or,

df['Phrase length'] = df['Phrase'].map(string_length)

UPDATE:

If you want to use input() to enter the column name of your choice then use the following:

def string_length(data):
    print("Please enter column name:")
    a = input()
    data[a+'_len'] = data[a].astype(str).apply(lambda x: len(x))

followed by:

string_length(df)

Enter the column name of your choice and then try printing the dataframe.

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