pandas 如何创建具有多值列的均值列

64jmpszr  于 2022-12-28  发布在  其他
关注(0)|答案(2)|浏览(105)

我用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

我已经绞尽脑汁了,真的需要尽快解决这个问题。谢谢。
非常感谢您的回复。

mepcadol

mepcadol1#

如果确实希望每个逗号和小数点都保持不变,那么最后一列必须是字符串类型,因为不能同时使用浮点数和字符串。
你可以使用pd.apply把任何大于1的列表元素转换成浮点数,取平均值,然后把结果转换回字符串类型。

df['pricerange_All_new'] = df['pricerange_All'].apply(lambda row: row[0] if len(row) == 1 else str(np.mean([float(p.replace(',','.')) for p in row])))

结果:

df
     pricerange_All pricerange_All_new
0           [16.51]              16.51
1           [17,61]              17,61
2           [16,96]              16,96
3           [13,70]              13,70
4           [17,85]              17,85
5  [690.94, 690.76]             690.85
z8dt9xmd

z8dt9xmd2#

假设您有一个如下所示的** Dataframe **(df):

df = pd.DataFrame({ 'pricerange_All': [['16.51'], ['17,61'], ['16,96'], ['13,70'], ['17,85'], ['690.94', '690.76']]})

print(df)

----------------------------

     pricerange_All
0           [16.51]
1           [17,61]
2           [16,96]
3           [13,70]
4           [17,85]
5  [690.94, 690.76]

您可以使用lambda函数statistics包中的mean函数应用于以下各项:

代码:

from statistics import mean 

df.pricerange_All = df.pricerange_All.apply(lambda x: mean(list(map(float, [item.replace(",", ".") for item in x]))))
print(df)

输出:

pricerange_All
0           16.51
1           17.61
2           16.96
3           13.70
4           17.85
5          690.85

备选项(保留逗号):

如果你想保留逗号,你可以这样做:

df.pricerange_All = df.pricerange_All.apply(lambda x: mean(list(map(float, [item.replace(",", ".") for item in x]))) if len(x) > 1 else x[0])
print(df)

输出:

pricerange_All
0          16.51
1          17,61
2          16,96
3          13,70
4          17,85
5         690.85

相关问题