python - 使用来自另一个 pandas DF 的最小值的 id 填充 pandas 列

标签 python pandas for-loop dataframe

我希望遍历 订单 列表并为每个订单分配所有者 idid 位于单独的 pandas dataframe 中(我也尝试将其更改为 SeriesOrderedDict。我想从 df 中找到最小值并将其用于 orders 中的第一个 order,然后将其计数加 1 idcount,重复直到所有订单都成交。

可重现的例子:

df = pd.DataFrame({'Id':['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 'count':[2, 3, 5, 6, 8, 9, 12, 13, 15, 55]})
orders = pd.DataFrame({'order_id':['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'a11', 'a12', 'a13']})
orders['newowner'] = ""

所有者:

df
  Id  count
0  a      2
1  b      3
2  c      5
3  d      6
4  e      8
5  f      9
6  g     12
7  h     13
8  i     15
9  j     55

订单:

   order_id newowner
0        a1         
1        a2         
2        a3         
3        a4         
4        a5         
5        a6         
6        a7         
7        a8         
8        a9         
9       a10         
10      a11         
11      a12         
12      a13         

预期结果:

   order_id newowner
0        a1       a    # brings a up to 3 records
1        a2       a    # a and b are tied with 3, so it goes to a again (doesn't matter which gets it first)
2        a3       b    # now b has 3, and a has 4, so it goes to b
3        a4       a    # both have 4 so a
4        a5       b    # etc.
5        a6       a
6        a7       b
7        a8       c
8        a9       a
9       a10       b
10      a11       c
11      a12       a
12      a13       b

我已经尝试找到 df.count 的最小值,并尝试遍历每个,但很难隔离每个订单。

for order in orders.iteritems():
    order['newowner'] = df.count.min()

for order in orders.iteritems():
    for name in df.iteritems:
        idx = df[df.count == df.count.min()]['Id']
    order['newonwer'] = idx

最佳答案

这是通过 df.apply 的一种方式:

def set_owner(order_id):
    min_idx = df['count'].idxmin()
    df.loc[min_idx, 'count'] += 1
    return df.loc[min_idx, 'Id']

orders['newowner'] = orders['order_id'].apply(set_owner)

orders
#    order_id newowner
# 0        a1        a
# 1        a2        a
# 2        a3        b
# 3        a4        a
# 4        a5        b
# 5        a6        a
# 6        a7        b
# 7        a8        c
# 8        a9        a
# 9       a10        b
# 10      a11        c
# 11      a12        d
# 12      a13        a

df
#   Id  count
# 0  a      8
# 1  b      7
# 2  c      7
# 3  d      7
# 4  e      8
# 5  f      9
# 6  g     12
# 7  h     13
# 8  i     15
# 9  j     55

关于python - 使用来自另一个 pandas DF 的最小值的 id 填充 pandas 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48601406/

相关文章:

python - 如何在交互模式下跳过 `if __name__ == "__main_ _"`?

python - 模拟类方法并更改 Python 中的一些对象属性

python - 有没有办法在打印时整理字典

python - python类型转换AttributeError : 'str' object has no attribute 'astype'

python - 比较 Pandas 数据框中的两行或多行

带有 CTL(复杂文本布局)语言的 python-docx add_style

python - 规范化遗漏波兰语字符

java - 字母打印直到整个单词最终以三角形的形式显示,Java

r - 如何跳过 R 'for' 循环中的增量?

bash:带有无符号整数的for循环