pandas 用明细表将费用分类

pxy2qtax  于 2024-01-04  发布在  其他
关注(0)|答案(1)|浏览(87)

我有一个固定的费用
| 日期|利贝莱|Prix|卡泰戈里耶|小类别|
| --|--|--|--|--|
| 2019 - 01 - 22| CB Darty xxxxxx| 100 |什么?|什么?|
| 2019 - 04 - 09| CB Restau Macdo xxx| 10 |什么?|什么?|
| 2019 - 01 - 10| VIR SALAIRE莫莫xxxx| 10000000 |什么?|什么?|
| 2019 - 04 - 11| VIR TUTU| 100 |什么?|什么?|
另一个框架2,它做链接之间的文类,次类和一些关键字
| 卡泰戈里耶|小类别|关键字|
| --|--|--|
| Courant| Alimentation|麦当劳、肯德基、汉堡王|
| Courant| Loisirs| Darty、UGC、Pathé|
| Pro| Revenus| Salaire,莫莫|
我想在python中,对于每一行的支出填充categorie和sous-categorie在字体的关键字,文可以找到在libellé列和使用第二个python.我是初学者在python,我不知道如何开始.
在我看来,一个选择是在Rumrame 2的行上执行for循环,对于列关键字中的每个关键字,在Rumrame expense的libellé列中搜索,如果匹配,将类别和子类别添加到expense中的行。但这将非常慢,也许有一个更好的方法可以用python来做。我在堆栈溢出中看到,关于这个主题一些其他问题,但没有类别、子类别和关键字

kgsdhlau

kgsdhlau1#

不清楚你想如何处理 *“1-lib:n-keywords”,反之亦然 *,但你仍然可以尝试这样做:

  1. def tkn(s):
  2. import re
  3. return set(re.split(",?\s+", s.lower()))
  4. matches = {
  5. kw: lib for kw, lib in product(df2["Keyword"], df1["Libellé"])
  6. if set(tkn(kw)).intersection(tkn(lib)) # is it sufficient ?
  7. }
  8. target = ["Catégorie", "Sous-catégorie"]
  9. out = (
  10. pd.merge(
  11. df1.drop(columns=target, errors="ignore"), df2[target],
  12. left_on="Libellé", right_on=df2["Keyword"].map(matches), how="left"
  13. )
  14. )

字符串
输出量:

  1. print(out)
  2. Date Libellé Prix Catégorie Sous-catégorie
  3. 0 01/01/22 CB Darty xxxxxx 100 Courant Loisirs
  4. 1 04/09/22 CB Restau Macdo xxx 10 Courant Alimentation
  5. 2 01/10/22 VIR SALAIRE MOMO xxxx 10000000 Pro Revenus
  6. 3 04/11/22 VIR TUTU 100 NaN NaN
  7. [4 rows x 5 columns]

展开查看全部

相关问题