首页 > 解决方案 > 获取 '@' 和 ';' 之间的子字符串 在“@”之前

问题描述

我有一个 pandas 列Amort,每一行都包含字符串值3,312.50 @ Mar 31, 2020; 3,312.50 @ Jun 30, 2020; 3,312.50 @ Sep 30, 2020; 3,312.50 @ Dec 31, 2020; 3,312.50 @ Mar 31, 2021,就像每一行一样,我想创建与每年关联的列,其中包含与每年关联的浮点数的总和值。因此,对于上面的字符串,新创建的列将是 3,312.50 * 4 Amort_2020。但是我已经意识到其中有一些价值,Amort所以0.64 @ Mar 31, 2020; 0.64 @ Jun 30, 2020; 0.64 @ Sep 30, 2020; 0.63 @ Dec 31, 2020; 0.64 @ Mar 31, 2021; 238.75 @ Jul 31, 2021我希望在下面构建的初始代码不起作用。我想知道是否有更好的方法来做我想做的事情。我研究过使用re,但想不出一个好的方法来做到这一点。

for i in range(0, df.shape[0]):
    if df['Amort'].iloc[i] is not None:
        l = []
        no_periods = (str(df['Amort'].iloc[i])).count('2020') ##for summation
        temp = (df['Amort'].iloc[i]).replace("@", "") 
        temp = temp.replace(",", "") ###so that I can convert to float
        for k in range(no_periods):
            l.append(float(temp[:8]))
        df['Amort_2020'].iloc[i] = sum(l)

编辑:

df['Amort']列中添加:

0    3,312.50 @ Mar 31, 2020; 3,312.50 @ Jun 30, 20...
1    1,137.50 @ Jun 17, 2020; 1,137.50 @ Sep 17, 20...
2    394.51 @ Jun 07, 2020; 394.50 @ Sep 07, 2020; ...
3    395.72 @ Jun 07, 2020; 395.73 @ Sep 07, 2020; ...
4    448.86 @ Jun 07, 2020; 448.87 @ Sep 07, 2020; ...
Name: Amort, dtype: object

预期产出: 2020 年 df['Amort_2020']

0    13250
1    3412.5
2    1183.53

所以,每年都这样。第 0 行包含3,312.50 @ Mar 31, 2020; 3,312.50 @ Jun 30, 2020; 3,312.50 @ Sep 30, 2020; 3,312.50 @ Dec 31, 2020; 3,312.50 @ Mar 31, 2021并且因为我想总结与每年相关的浮点值,对于 2020 年有 4 个这样的 3312.5 值,所以它将是 3312.5*4 = 13250。第一行具有浮点数乘以 4 和行 1 和2 的浮点数乘以 3,因为 2020 年仅出现 3 次

标签: pythonpandas

解决方案


IIUC,您可以使用extractall

s = df.Amort.str.extractall('(?P<Amort>[\d,\.]+) \@ (?P<date>[\w ,]+);')

s['date'] = pd.to_datetime(s['date'])
s['Amort'] = s['Amort'].str.replace(',','').astype(float)
s = s.reset_index('match',drop=True).set_index(s['date'].dt.year.rename('year'), append=True)

s.groupby(level=(0,1)).Amort.sum()

输出:

   year
0  2020    6625.00
1  2020    2275.00
2  2020     789.01
3  2020     791.45
4  2020     897.73
Name: Amort, dtype: float64

推荐阅读