在 pandas 中查找先前匹配的单元格的索引

Find index of previously matched cell in pandas

我有一段时间没有使用 python 如果这是一个愚蠢的问题,我深表歉意!

我有一个大面板数据集,多个 ID 需要多天。我们称这个为 data1

我还有 data2,这是属于特定类别的 ID 列表。

我想:

  1. data1

    中的 data2 获取每个 ID 的最后一天
  2. 获取 code 列中与 data1 行对应的值

我目前拥有的是:

for i in data2.id.unique():
    last_day = data1[data1["ID"]==i]["datestamp"]
    code = data1[(data1["ID"==i])&(data1["datestamp"]==last_day)]["code"]

编辑:我想出了一个合并两者的代码,所以现在新数据集看起来像这样:

ID | length | code | payments
01 | 230    | AAA  | 1
02 | 106    | BBB  | 4
03 | 128    | CCC  | 2
04 | 96     | AAA  | 3
05 | 205    | CCC  | 5

其中 length 是客户在公司工作的天数。

基本上我想说的是,当代码是AAA或CCC时,新列new取长度值,而不是AAA或CCC时取0.

我试过这样做:

df['new']=[df['length'] for x in df['code'] if x in ["AAA","CCC"]]

但这没有用。然后我这样尝试:

hello=[df['length'] for x in df['code'] if x in ["AAA","CCC"]]

它起作用了,但每次满足条件时它都会返回完整系列 df["length"]。我不确定如何做到这一点,以便在满足条件时应用 length 中的值。

我认为您希望根据 code 中的值将 length 的副本复制到 new 中。

IIUC,你想要这个。

import pandas as pd
c = ['ID','length','code']
d = [['01',230,'AAA'],
['02',106,'BBB'],
['03',128,'CCC'],
['04',96,'AAA'],
['05',205,'CCC']]

df = pd.DataFrame(d,columns=c)
print (df)

df['new'] = df.apply(lambda x: x['length'] if x['code'] in ['AAA','CCC'] else 0, axis=1)
print (df)

axis=1,它将按行处理逻辑。它将结果发送到 df['new'].

原始数据帧:

   ID  length code
0  01     230  AAA
1  02     106  BBB
2  03     128  CCC
3  04      96  AAA
4  05     205  CCC

更新数据框:

   ID  length code  new
0  01     230  AAA  230
1  02     106  BBB    0
2  03     128  CCC  128
3  04      96  AAA   96
4  05     205  CCC  205