我是 Python 的初學者。我有一個名為df_opensports的 df ,有很多列。一列被命名為'Sub_Categoria'。另一列名為'Name'。我需要用同一“名稱”列索引中的第一個單詞填充“Sub_Categoria”中的空值。例如,如果在 df_opensports 的 idx 10 中,來自 'Sub_Categoria' 的值為空,則使用同一索引中的 'Name' 字串中的第一個單詞填充它。我看過很多帖子,并嘗試了不同的方法,例如:
df_opensports.loc[df_opensports.Sub_Categoria == '', 'Sub_Categoria']=df_opensports.Name.str.split().str.get(0)
但是'Sub_Categoria'中每個空值的結果仍然是空的......我在做什么錯?
de df 的一個例子:

例如,在第一行中,我需要獲取“mocasines”而不是 NaN
提前致謝
uj5u.com熱心網友回復:
不是最好的主意,但我相信它會解決您的問題:
for index, row in df_opensports.iterrows():
if row["Sub_Categoria"] == None:
df_opensports.loc[index, "Sub_Categoria"] = row["Name"].split(" ")[0]
感謝您的評論,我記得這個問題的另一種方法:
df_opensports.Sub_Categoria.fillna(df_opensports.Name.apply(lambda x: x.split(" ")[0]), inplace=True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429470.html
