映射并替换为值列表Python

时间:2020-07-15 05:23:29

标签: python pandas numpy

我有两个数据帧:df1是ID表。我想用它来调整Item_Id中的df2。我想这样做:Item_Id中的df2等于Namedf1中的数值,用相应的Item_Id中的Id替换df1 df1

Id Name 2 Item 002 3 Item 003 4 Item 004 5 Item 006 6 Item 007 7 Item 008 8 Item 009 9 Item 010 ...

df2

Id Timestamp value Item_Id Date 2371 2412 2017-12-15 16:05:50.653 27.0 2 2017-12-15 2373 2414 2017-12-15 16:05:50.653 25.0 3 2017-12-15 2375 2416 2017-12-15 16:05:50.653 42.0 4 2017-12-15 2377 2418 2017-12-15 16:05:50.653 25.0 7 2017-12-15 2379 2420 2017-12-15 16:05:50.653 25.0 10 2017-12-15

        Id      Timestamp               value   Item_Id Date    
2371    2412    2017-12-15 16:05:50.653 27.0    2       2017-12-15   
2373    2414    2017-12-15 16:05:50.653 25.0    3       2017-12-15
2375    2416    2017-12-15 16:05:50.653 42.0    4       2017-12-15  
2377    2418    2017-12-15 16:05:50.653 25.0    6       2017-12-15  
2379    2420    2017-12-15 16:05:50.653 25.0    9       2017-12-15  

预期输出:

#include <functional>
#include <iostream>

struct X
{
  struct Wrapper
  {
    Wrapper(std::function<void(int)> pfn)
      : fn(pfn)
    { }
    Wrapper(std::function<void()> pfn)
      : fn([pfn](int) { pfn(); })
      { }

    void operator()()
    {
      fn(0);
    }

    void operator()(int v)
    {
      fn(v);
    }

    std::function<void(int)> fn;
  };

  X(std::function<void()> pfn)
    : fn(pfn)
  { }
  X(std::function<void(int)> pfn)
    : fn(pfn)
  { }

  Wrapper fn;

};

int main()
{
  X x1([]() { std::cout << "no arg" << std::endl; });
  X x2([](int arg) { std::cout << "int arg = " << arg << std::endl; });
  
  x1.fn();
  x2.fn(100);

  return 0;
}

2 个答案:

答案 0 :(得分:1)

根据上面的评论,尝试以下操作:

# convert the string to a number
df1['Id2'] = df1['Name'].map(lambda x: int(x.split()[-1]))
# set this column as index so you can 'join'
df1.set_index('Id2', inplace=True)
# overwrite `Item_Id`
df2['Item_Id'] = df1.loc[df2['Item_Id'], 'Id']

答案 1 :(得分:1)

IIUC,使用maps = df["Name"].str.extract("(\d+)", expand=False).astype(int) mapper = df.set_index(s)["Id"].to_dict() df2["Item_Id"] = df2["Item_Id"].map(mapper) print(df2)

        Id                Timestamp  value  Item_Id        Date
2371  2412  2017-12-15 16:05:50.653   27.0        2  2017-12-15
2373  2414  2017-12-15 16:05:50.653   25.0        3  2017-12-15
2375  2416  2017-12-15 16:05:50.653   42.0        4  2017-12-15
2377  2418  2017-12-15 16:05:50.653   25.0        6  2017-12-15
2379  2420  2017-12-15 16:05:50.653   25.0        9  2017-12-15

输出:

rest-assured