簡體   English   中英

如何將此字符串長度函數應用於數據框中的列?

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

我寫了一個返回字符串長度的函數,

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

我有一個名為film的數據集,其中有一列名為Phrase 我想向我的數據集添加一個新列,它將我的函數應用於 Phrase 列並輸入短語中每個值的字符串長度。

我嘗試使用以下代碼:

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

但是,這會返回錯誤:

類型錯誤:string_length() 采用 0 個位置參數,但給出了 1 個

我需要做什么來修復此代碼?

我確定我錯過了一些非常愚蠢的東西,但我對 python 還是很陌生!

該函數提示用戶進行一些輸入。 如果您將其應用於數據幀,這將不起作用。 但是,您可以應用內置的 len() 函數:

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

如果我正確理解您的問題,那么您一定是在尋找這個:

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

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

或者,

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

更新:

如果您想使用 input() 輸入您選擇的列名,請使用以下命令:

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

其次是:

string_length(df)

輸入您選擇的列名,然后嘗試打印數據框。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM