【问题标题】:replace values for specific rows more efficiently in pandas / Python在 pandas / Python 中更有效地替换特定行的值
【发布时间】:2021-04-06 08:26:35
【问题描述】:

我有两个数据框,基于从列表中获得的条件(长度为 200 万),我得到与该条件匹配的行,然后对于这些行,我更改第一列 x 和 y 中的值数据帧由第二个数据帧中的 x 和 y 的值。这是我的代码,但它非常慢并且使我的计算机死机。知道如何更有效地做到这一点吗?

for ids in List_id:
    a=df1.index[(df1['id'] == ids )==True].values[0]
    b=df2.index[(df2['id'] == ids )==True].values[0]
    df1['x'][a] = df2['x'][b]
    df1['y'][a] = df2['y'][b]

谢谢

--

例子:

List_id=[1, 11, 12, 13]

ids=1

a=df1.index[(df1['id'] == 1 )==True].values[0]

打印('a'):234

b=df2.index[(df2['id'] == 1 )==True].values[0]

打印('b'):789

df1['x'][a] = 0

df2['x'][b] =15

所以最后我想在我的数据框 1 中:

df1['x'][a] = df2['x'][b]

【问题讨论】:

  • 请分享示例输入和预期输出
  • 我举个简单的例子,谢谢

标签: pandas loops


【解决方案1】:

假设您在两个数据框中都没有重复的 id,您可以尝试如下操作:
第 1 步:过滤 df2
第 2 步:将 df1 与过滤后的一个连接
第 3 步替换加入的 df 中的值并删除额外的列。

df2_filtered=df2[df2['id'].isin(List_id)]
join_df = df1.setIndex('id').join(df2_filtered.setIndex('id'), rsuffix = "_ignore", how = 'left')
# other columns from df2 will be null, you can use that to get the rows which needs to be updated

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-20
    • 2022-07-11
    • 2018-11-11
    • 2022-10-24
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多