![](/img/trans.png)
[英]Creating a new column containing specified ranges based on values in a column of a Pandas Dataframe
[英]Pandas, creating a column based on ranges
我正在嘗試根據另一列的條件創建一個新列,該列具有該計數范圍。 但是,我得到一個 ValueError:一個系列的真值是模棱兩可的。 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
我試圖兩次使用同一列來確定范圍,但它不起作用。 問題出在哪里?
df.loc[(df["count_words"] > 100 & df["count_words"] <= 300), "length"] = "keskipitkä"
df.loc[df["count_words"] <= 100, "lenght"] = "lyhyt"
df.loc[df["count_words"] > 300, "length"] = "pitkä"
問題出在()
中,因為運算符的優先級:
df.loc[(df["count_words"] > 100) & (df["count_words"] <= 300), "length"] = "keskipitkä"
另一個想法是在這里使用cut
:
df=pd.DataFrame({'count_words':[10, 100, 200, 300, 4999]})
df["lenght"] = pd.cut(df["count_words"],
bins= [-np.inf, 100, 300, np.inf],
labels=['lyhyt','keskipitkä','pitkä'])
print (df)
count_words lenght
0 10 lyhyt
1 100 lyhyt
2 200 keskipitkä
3 300 keskipitkä
4 4999 pitkä
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.