【问题标题】:How to speed up dataframe search and assign value? [duplicate]如何加快数据框搜索和赋值? [复制]
【发布时间】:2017-09-14 12:58:11
【问题描述】:

例如,我有两个数据框

df1:

        0        1           2           3 
0      Name     Unit      Attribute     Date
1      a        A           xxy         xxx
2      b        B           xyx         xxx
3      c        C           xxx         xxx
4      d        D           yxx         xxx
5      e        E           yxy         yyy

df2:

        0        1        2       
      Name     Unit      Date
0      a        F        xxx
1      b        G        xxx
2      e        H        xxx
3      f        I        xxx

我想用 df2 中的相应条目覆盖 df1 中的条目。

例如,用 df2.loc[2,2] 覆盖 df1.loc[5,3]。也就是说,对于具有相同'Name'的行,如果df1在df2中,则覆盖df1的同一列。

目前,我正在以一种愚蠢的方式这样做:

def find_column_num(key, df_name, start_row, stop_row, start_column, stop_column):
    for i in range(start_row,stop_row+1):
        for j in range(start_column, stop_column+1):
            if df_name.loc[i,j]== key:
                column_num_with_key = j
                return column_num_with_key
                break 

for i in range(0,len(df1.index)):
    for ii in range(0,len(df2.index)):
       if df1.loc[i,0] == df2.loc[ii,0]:
          for j in range(0,len(df1.columns)):
              if df1.loc[0,j] in df2.loc[0,:]:
                   df1.set_value(i,j, df2.loc[ii,find_column_num(df1.loc[0,j],df2,0,0,0,len(df2.columns))]

我并不以此为荣。我做了一些研究,想出了用 set_value() 替换 '=',这很有帮助。我真的很期待听到其他建议。实际问题的大小是 200 行和 30 列。因此,运行所有 for 循环需要 20 秒。

【问题讨论】:

  • 输出是什么?
  • 预期输出...请。你需要merge
  • 下一次,请不要发布所有值相同 (xxx) 的不干净、不可加载的输入。这让测试变得毫无意义。
  • 感谢您的评论。我已经更改了代码并在 jupyter notebook 中对其进行了测试。
  • 您好,COLDSPEED,谢谢您的帮助。我试过你的答案,但没有奏效。同时,我已经正式确定了我的问题,以便可以运行它并获得预期的输出。你能再看看这个问题吗?也许你会看到我努力实现的目标?

标签: python pandas dataframe


【解决方案1】:

IIUC,使用mergefillna。您需要稍微清理一下数据。这是我用来参考的。

 df1

  Name Unit Attribute Date
0    a    A       xxy  xxx
1    b    B       xyx  xxx
2    d    C       xxx  xxx
3    e    D       yxx  xxx
4    e    E       yxy  xxx

df2

  Name Unit Date
0    a    F  xxx
1    b    G  xxx
2    e    H  xxx
3    f    H  xxx

out = df1[['Name', 'Attribute']].merge(df2, how='left').fillna(df1)
out

  Name Attribute Unit Date
0    a       xxy    F  xxx
1    b       xyx    G  xxx
2    d       xxx    C  xxx
3    e       yxx    H  xxx
4    e       yxy    H  xxx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-14
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    相关资源
    最近更新 更多