【问题标题】:how to check exist in a string an element from another string and replace it in python如何检查字符串中是否存在来自另一个字符串的元素并在python中替换它
【发布时间】:2022-10-13 12:43:19
【问题描述】:

我有以下数据框

     Account    Buy/Sell    Amount  month
1    1001       Sell        52792   2021-Automation-Aug-Dummy.xlsx
5    3001       Buy         85802   2021-Automation-Aug-Dummy.xlsx
8    5601       Buy         10425   2021-Automation-Aug-Dummy.xlsx
11   2001       Buy         12526   2021-Automation-Aug-Dummy.xlsx
14   98071      Sell        90517   2021-Automation-Aug-Dummy.xlsx
... ... ... ... ... ... ...

我想替换月份的 abv 名称,而不是 'month' 列中的长名称。 例如'2021-Automation-Aug-Dummy.xlsx'应该替换为'八月'.

我已经编写了以下代码,但它不能替换 abv。

month_abv = ['Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov']
for inx in test.index:
    if any(abv in month_abv for abv in test.loc[inx,'month']):
        test.loc[inx,'month']= abv

但它不会改变数据框。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    利用:

    month_abv = ['Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov']
    pat = '|'.join(r"{}".format(x) for x in month_abv)
    test['month']= test['month'].str.extract(rf'({pat})', expand=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-24
      • 2017-09-23
      • 1970-01-01
      • 2023-03-22
      • 2017-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多