簡體   English   中英

如何用 python (熊貓)的另一列的值替換 None 的列值?

[英]How to replace a column value of None with a value from another column with python (pandas)?

我有一個 DataFrame ,其中第一列代表顏色,第二列代表項目的描述。 不幸的是, Color列的一些信息被合並到Description列中,如下所示:

data = {"Color": [None, "Red", "Blue", "Green", None],
        "Description": ["Red T-Shirt", "Skirt", "Pants", "Underwear", "Blue Cap"]}

df = pd.DataFrame(data)


| Color | Description |
|-------|-------------|
|None   |Red T-Shirt  |
|Blue   |Pants        |
|Green  |Underwear    |
|None   |Blue Cap     |

首先,我將空間上的Description列拆分為:

df["Description"] = df["Description"].apply(lambda x: x.split(" "))

我想要做的是將Color上的None值替換為Description的第一個元素,其中Color is None 我使用的代碼是:

colors = ["Red", "Blue", "Green"]
df["Color"] = df["Color"].where(df["Color"] != None, df["Description"][0])
df["Color"] = df["Color"].apply(lambda x: x if x in colors else "Color N/A")

我的代碼返回以下信息:

| Color | Description      |
|-------|------------------|
|None   |["Red", "T-Shirt"]|
|Blue   |["Pants"]         |
|Green  |["Underwear"]     |
|None   |["Blue", "Cap"]   |

但應該返回:

| Color | Description      |
|-------|------------------|
|Red    |["Red", "T-Shirt"]|
|Blue   |["Pants"]         |
|Green  |["Underwear"]     |
|Blue   |["Blue", "Cap"]   |

知道我犯了哪個錯誤嗎?

嘗試這個 -

根據空格字符拆分第二列,然后使用 np.where 填充“顏色”列中的 Null 值。

df['Description'] = df['Description'].str.split(' ')
df['Color'] = np.where(df['Color'].isna() , df['Description'].str[0], df['Color'])
print(df)

您可以通過設置axis=1在行上使用apply() 如果Color列的值為None ,詳細信息將返回Description列的第一個值。

df["Description"] = df["Description"].apply(lambda x: x.split(" "))

df['Color'] = df.apply(lambda row: row['Description'][0] if row['Color'] == None else row['Color'], axis=1)
print(df)

   Color     Description
0    Red  [Red, T-Shirt]
1    Red         [Skirt]
2   Blue         [Pants]
3  Green     [Underwear]
4   Blue     [Blue, Cap]

您可以使用 loc function,您可以在其中根據任何給定條件更新列

data.loc[data['Color'].isnull(), 'color'] = data['Description'][0]

暫無
暫無

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

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