简体   繁体   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

How can I update the location values in df1 based on the condition that latitude is between min_latitude and max_latitude just like the result below?如何根据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

I have tried using df1['location'].apply(lambda x: df2['location'] if df1['location'].between(df2['min_latitude'], df2['max_latitude']) else df1['location']) , but it returns ValueError: Can only compare identically-labeled Series objects .我试过使用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

You don't need to use between, you can use boolean indexing and get what you want with:您不需要使用 between,您可以使用布尔索引并获得您想要的:

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

and something similar for point_b.和 point_b 类似的东西。 You could do many points by iterating through a list of points as well.你也可以通过遍历一个点列表来做很多点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据 pandas 中的条件匹配从另一个数据帧更新数据帧列值 - How to update the data frame column values from another data frame based a conditional match in pandas 如何根据极坐标中的条件匹配从另一个数据框中更新数据框列值? - How to update the data frame column values from another data frame based a conditional match in polars? 我需要基于列名从一个数据框到另一个数据框的值在 python pandas 中 - I need values from one data frame to another data frame in python pandas based on column name Pandas:根据另一个数据框列中的值范围计算单独数据框列框中的值(python) - Pandas: Calculating a value in a separate data frame column frame based on range of values in another data frame column (python) Python Pandas 数据帧 基于另一列的计数值 - Python Pandas Data Frame Count values of one column based on another Python Pandas-使用另一个数据框列的值更新数据框列 - Python Pandas-Update a data frame column with values from another Python:根据另一个数据框中的日期范围更新列的值 - Python : Update Values of a Column based on Date Range from another Data Frame 如何根据python中的列值创建自定义数据框? - How to create a customised data frame based on column values in python? 根据来自另一个数据框的值移动列值 - MOVING column values based on values from another data frame 如何根据值是否存在于另一个数据框中从数据框中删除值? - How do you remove values from a data frame based on whether they are present in another data frame?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM