【问题标题】:Dataframe Lookup function to return multiple matches数据框查找函数返回多个匹配项
【发布时间】:2022-01-02 06:51:37
【问题描述】:

我有两个数据框如下:

Credits:

       ID  Account     Credits       Date
0     122     1234    30546.45 2017-02-16
1   40058     2345   200000.00 2019-04-04
2   53133     2345    30495.82 2019-09-12
3   91437     3456  1725000.00 2020-04-13
4  133686     4567   500000.00 2019-08-28
5  134792     4567  1448887.50 2019-11-22
6  135794     4567   400000.00 2020-02-04
7  137555     4567   500000.00 2020-08-10


Debits:

        ID  Account      Debits       Date
0    49020     7405   871140.57 2019-06-21
1    63274     9714  1725000.00 2020-04-13
2    64788     5351  1448887.50 2019-11-22
3    94443     5678  1725000.00 2020-04-15
4    92868     5678   525000.00 2020-03-27
5   123732     6789    30495.82 2019-09-13
6   125585     7890   200000.00 2019-04-04
7   138182     8901   930088.80 2019-12-31
8   137829     8901   700000.00 2019-12-09
9   135588     8901   200000.00 2019-04-04
10  143025     9012   500000.00 2019-08-28
11  143451     9012   500000.00 2020-08-10
12  143212     9012   400000.00 2020-02-04

(实际上,这两个数据帧都有数十万行长,但我在此示例中将它们缩短了。)

我想要的是遍历Credits['Credits'] 中的每个数字金额,并在Debits['Debits'] 中找到Credit 日期后3天内的所有对应金额。

所以最终结果(在一个新的数据框中)应该是这样的:

CreditsMatch
     MatchID
0  N/A
1  [125585,135588]
2  123732
3  [63274,94443]
4  143025
5  64788
6  143212
7  143451

我写了这个函数:

def Match(SearchCr, SearchDate):
    if not pd.isnull(SearchCr):
        SearchDtLo = SearchDate - timedelta(3)
        SearchDtHi = SearchDate + timedelta(3)
        filt_Debits = []
        filt_Debits = Debits.query('Debits == @SearchCr and `Date` >= @SearchDtLo and `Date` <= @SearchDtHi and `Account` != @SearchAcct')
        Matchlist = filt_xferdbdf['ID'].tolist()        
        return Matchlist

如果我在列表中的单个项目上运行它,它工作正常。

但是当我尝试使用这个将它应用到 Credits 列时:

CreditsMatch['MatchID'] = Credits['Credits'].apply(lambda x: Match(x['Credits'], x['Date'], axis =1))

我收到此错误:

TypeError: 'float' object is not subscriptable

谁能指出我正确的方向?

【问题讨论】:

    标签: python pandas dataframe typeerror


    【解决方案1】:

    Credits['Credits'].apply 将调用指定函数一次系列中的每个项目。所以xfloat,因为Credits['Credits'] 包含浮点数。

    由于您尝试在函数中访问 Credits['Credits']Credits['Date'],因此您似乎在尝试为每一行运行该函数。为此,请在整个 Credits 数据帧上调用 apply,而不仅仅是 Credits['Credits'] 系列。

    改变这一行:

    CreditsMatch['MatchID'] = Credits['Credits'].apply(lambda x: Match(x['Credits'], x['Date'], axis =1))
    

    到这里:

    CreditsMatch['MatchID'] = Credits.apply(lambda x: Match(x['Credits'], x['Date'], axis=1))
    

    (Credits['Credits'].applyCredits.apply)

    【讨论】:

    • 还是没有运气。现在它说“KeyError:'Credits'”
    • 发送print(Credits.head().to_dict())的输出
    猜你喜欢
    • 2021-09-30
    • 2016-12-24
    • 2021-08-29
    • 2022-09-23
    • 2021-08-12
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多