我用str.findall创建了一个新列()方法,因为原始值是一个句子,如“Preis ab 23,48 EUR pro Person/Tag”,所以我提取了数字['23,48']作为新值,但有些句子包含两个价格,如“from €83 to €120”,所以我会得到新值['83','120'],现在,我想用平均值替换包含两个值的行,但找不到解决方案
提取方法如下:
df['pricerange_All'] = df.pricerange.str.findall(r'([0-9,.]+(?:\.[0-9,.]+)?)')
Dataframe 是这样的:
pricerange_All
0 ['16.51']
1 ['17,61']
2 ['16,96']
3 ['13,70']
4 ['17,85']
.
100 ['690.94', '690.76']
如您所见,一些值有两个价格
我试过解决办法:
df2= pd.DataFrame([pd.Series(x) for x in df.pricerange_All])
df2.columns = ['price_{}'.format(x+1) for x in df2.columns]
但没有成功
如何分隔列或创建一个新列,保存每行的平均值?如:
mean_price
0 16.51
1 17,61
2 16,96
3 13,70
4 17,85
. .
100 690.85
我已经绞尽脑汁了,真的需要尽快解决这个问题。谢谢。
非常感谢您的回复。
2条答案
按热度按时间mepcadol1#
如果确实希望每个逗号和小数点都保持不变,那么最后一列必须是字符串类型,因为不能同时使用浮点数和字符串。
你可以使用
pd.apply
把任何大于1的列表元素转换成浮点数,取平均值,然后把结果转换回字符串类型。结果:
z8dt9xmd2#
假设您有一个如下所示的** Dataframe **(df):
您可以使用lambda函数将statistics包中的mean函数应用于以下各项:
代码:
输出:
备选项(保留逗号):
如果你想保留逗号,你可以这样做:
输出: