簡體   English   中英

如何根據 Python 中另一個數據框的值更新數據框中列的值?

[英]How do I update the values of a column in a data frame based on the values of another data frame in Python?

df1
  | location | latitude
0 | NaN      | 41.0
1 | NaN      | 43.0
2 | NaN      | 72.0
3 | NaN      | 74.0

df2
  | location | min_latitude | max_latitude
0 | point_a  | 40.0         | 45.0
1 | point_b  | 70.0         | 75.0

如何根據latitude介於min_latitudemax_latitude之間的條件更新df1location值,就像下面的結果一樣?

df1
  | location | latitude
0 | point_a  | 41.0
1 | point_a  | 43.0
2 | point_b  | 72.0
3 | point_b  | 74.0

我試過使用df1['location'].apply(lambda x: df2['location'] if df1['location'].between(df2['min_latitude'], df2['max_latitude']) else df1['location']) ,但它返回ValueError: Can only compare identically-labeled Series objects

您不需要使用 between,您可以使用布爾索引並獲得您想要的:

df1["location"][(df1["latitude"] > df2["min_lattitude"]["point_a"]) & (df1["latitude"] < df2["max_lattitude"]["point_a"])] = "point_a"

和 point_b 類似的東西。 你也可以通過遍歷一個點列表來做很多點。

暫無
暫無

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

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