从多个分隔值计算平均值

问题描述 投票:0回答:1

我有很多excel文件用作笔记本/纸,但是模板是一样的。我正在尝试从它们创建一个数据框。

许多单元格都有多个价格数值,我想提取这些数值并找到它们的平均值,不包括日历年(例如 2019)。

假设单元格中的文本是:2019 年最低 59 万美元。初始报价为 65 万美元。 但我永远不知道里面有多少个数值,可能是1可能是5.

我想要的是获得除年份之外的所有值的平均值。所以在这个例子中: (590+650)/2=620

这是我到目前为止所得到的:

s=df['Price'].str.findall('\d+')
df['Price1'] = s.apply(lambda x: '_'.join(i for i in x if int(i)<2000))

这给出了输出:

590_650

然后得到一个平均值:

df['Price1'].str.split('_').apply(lambda x : (float(x[0])+float(x[1]))/2)

但是问题是我并不总是有 2 个值,可能是 1,也可能是 5。所以我想要一些可以随时应用的通用的东西。

感谢任何帮助。

python pandas
1个回答
0
投票

没有辅助柱的解决方案

join
:

s=df['Price'].str.findall('\d+')
df['Price2'] = s.apply(lambda x: np.mean([float(i) for i in x if int(i)<2000]))

或:

s=df['Price'].str.extractall('(\d+)')
df['Price2'] = s[0].astype(float).loc[lambda x: x < 2000].groupby(level=0).mean()

辅助列的解决方案:

s=df['Price'].str.findall('\d+')
df['Price1'] = s.apply(lambda x: '_'.join(i for i in x if int(i)<2000))
df['Price2'] = df['Price1'].str.split('_', expand=True).astype(float).mean(axis=1)
© www.soinside.com 2019 - 2024. All rights reserved.