簡體   English   中英

Pandas 錯誤:序列項 0:預期的 str 實例,找到 NoneType

[英]Pandas Error: sequence item 0: expected str instance, NoneType found

我有一個 dataframe 如下:

Car_Modal    Color     Number_Passenger
Proton       Black     5
Proton       Black     7
Perudua      White     5
Perudua      White     7
Perudua      Red       7
Honda                  5

由於本田行在顏色列有 Null 值,當我使用以下代碼時顯示錯誤:

df["Join"]=df.groupby("Car_Modal")["Color"].transform(lambda x:'<br>'.join(x.unique()))

預期 Output:

Car_Modal    Color     Number_Passenger     Join
Proton       Black     5                    Black
Proton       Black     7                    Black
Perudua      White     5                    White<br>Red
Perudua      White     7                    White<br>Red
Perudua      Red       7                    White<br>Red
Honda                  5 

任何人都可以分享我的想法如何解決這個問題?

嘗試過濾不是 null 的數據

df["Join"]=df[~df["Color"].isnull()].groupby("Car_Modal")["Color"] \
    .transform(lambda x :'<br>'.join(x.unique()))

您可以使用pandas.Series.notnull構建一個過濾器以根據特定列中是否存在 null 值進行過濾:

filter_Color_null=df['Color'].notnull()
df["Join"]=df[filter_Color_null].groupby("Car_Modal")["Color"].transform(lambda x :'<br>'.join(x.unique()))

您還可以使用DataFrame.notnull按 DataFrame 的任何列進行過濾:

filter_null=df.notnull().all(axis=1)
df["Join"]=df[filter_null].groupby("Car_Modal")["Color"].transform(lambda x :'<br>'.join(x.unique()))

暫無
暫無

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

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