python - 获取 '@' 和 ';' 之间的子字符串 在“@”之前
问题描述
我有一个 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 次
解决方案
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
推荐阅读
- go - 查询 FlagSet 使用情况
- python - Python selenium 从表中提取数据并单击
- android - 单击 Listview Android 上的项目时显示按钮
- ansible - 为什么我的 Ansible 复制命令意外挂起?
- java - 一定数量的代理延迟
- vue.js - Vuejs分页与bootstrap 4不兼容
- magento - 我正在调用 Magento getFormKey() 方法,它没有返回任何内容
- react-native - 如何使 FlatList 填充高度?
- nfs - NT_STATUS_ILLEGAL_CHARACTER 在 Owncloud 服务器 10.0.9 上使用 SMB 外部存储时出错
- r - 用它的子组替换匹配的字符串