簡體   English   中英

Dataframe,創建一個新列,其值基於另一列的索引

[英]Dataframe, creating a new column with values based on another column's indices

我想創建一個新列並根據索引號從第二列中為其提供值。

dataframe 是df4 現有列是SalePrice ,我要創建的新列是Label

我希望Label具有 3 個不同的值,具體取決於SalePrice的索引號,因為SalePrice是根據其值排序的。

這是我的做法:

df4.loc[df4.SalePrice.index<int(len(df4.SalePrice.index)/3),"Label"]="Expensive"
df4.loc[df4.SalePrice.index>int(len(df4.SalePrice.index)/3),"Label"]="medium" 
df4.loc[df4.SalePrice.index>int(len(df4.SalePrice.index)*2/3),"Label"]="Low" 

所以這行得通,但我認為可能有更有效和更好的方法來做到這一點......我嘗試在第二個命令行中使用一個范圍

df4.loc[df4.SalePrice.index>int(len(df4.SalePrice.index)/3)& df4.SalePrice.index<int(len(df4.SalePrice.index)*2/3),"Label"]="Medium"

但后來我得到:

"TypeError: unsupported operand type(s) for &: 'int' and 'RangeIndex'"

我將不勝感激!

你快到了。 你只需要放置一些括號:

df4.loc[(df4.SalePrice.index>int(len(df4.SalePrice.index)/3)) & (df4.SalePrice.index<int(len(df4.SalePrice.index)*2/3)),"Label"]="Medium"

每個語句必須在括號(...) & (...)中,否則 pandas 無法解析過濾器。

您還可以通過提取過濾器來重構您的代碼:

    mask_expensive = df4.SalePrice.index < int(len(df4.SalePrice.index)/3)
    mask_low = df4.SalePrice.index > int(len(df4.SalePrice.index)*2/3)
    mask_medium = (~ mask_expensive) & (~ mask_low)
    df4.loc[mask_expensive,"Label"]="Expensive"
    df4.loc[mask_medium ,"Label"]="medium" 
    df4.loc[mask_low,"Label"]="Low" 

通過這樣做,您的代碼更易於閱讀。 此外,這修復了您的代碼中的一個小錯誤,因為之前沒有定義==案例。

暫無
暫無

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

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