Reputation: 1
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!
Upvotes: 0
Views: 2137
Reputation: 2472
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.
Upvotes: 0
Reputation: 155
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)
Upvotes: 2