簡體   English   中英

正確使用 map 和 loc

[英]Using map and loc properly

這是我的代碼

df[df.loc[:,'medium']=='appsflyer']['source'] = df[df.loc[:,'medium']=='appsflyer'].['source'].map(lambda x: x if x in appsflyer else "Others")

變量“appsflyer”是一個包含我想要保留的所有值的列表。 如果它不在列表中,我想將該值標記為“其他”。

因為我只想更改 appsflyer 媒體中的值,所以我使用 loc 運算符來分割我的日期幀。

代碼正在運行,沒有警告或錯誤,但值根本沒有改變。

這里出了什么問題?

通過在作業中使用鏈式索引,您正在創建 dataframe 的副本。請參閱: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a -復制

df[df.loc[:, "medium"] == "appsflyer"]["source"].map(lambda x: x if x in appsflyer else "other")

這部分產生了正確的 output,但是由於結果被分配給了一個副本,所以原始 dataframe 中的值沒有被修改。

您可以做的是直接對 dataframe 進行切片,以便只選擇要更改的行。 例如:

df = pd.DataFrame({
"medium": ["appsflyer", "appsflyer", "not_appsflyer", "not_appsflyer"], 
"source": [1, 2, 3, 4]})
appsflyer = [1, 4]
df
          medium  source
0      appsflyer       1
1      appsflyer       2
2  not_appsflyer       3
3  not_appsflyer       4

我們需要 select 行 a) 在中間列中具有值“appsflyer”和 b) 在源列中其值不在 appsflyer 列表中(因此不是 1 或 4)。

這兩種情況的掩碼如下所示:

mask = (df.medium == "appsflyer") & ~(df.source.isin(appsflyer))

現在,我們可以簡單地將其用作 loc 中的行索引,並避免鏈接多個索引:

df.loc[mask, "source"] = "other"

df
          medium source
0      appsflyer      1
1      appsflyer  other
2  not_appsflyer      3
3  not_appsflyer      4

IIUC,嘗試where

  • 保留行的原始“來源”,其中:
    • 媒體不是“appsflyer”或
    • 媒體是“appsflyer”,“來源”在appsflyer列表中
  • 對於 rest,將來源更改為“其他”
df["source"] = df["source"].where(df["medium"].ne("appsflyer")|df["source"].isin(appsflyer)|,"Others")

暫無
暫無

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

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