Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 数据帧列中两个值的平均值_Python_Pandas - Fatal编程技术网

Python 数据帧列中两个值的平均值

Python 数据帧列中两个值的平均值,python,pandas,Python,Pandas,我试图得到价格的平均值 import pandas as pd df = pd.read_csv('sample_data1.csv') #文件样本 Name,Price Eedor,"¥1,680" Avidlove,"¥11,761" Fitment, Vintage,$8.95 - $16.95 silhouette,$27.80 - $69.50 Silk,$50.02 我试图得到“价格”栏中的平均值,如果是日元兑换美元,我已经编写了这个小函数,应该可以完成这项工作,我不知道如何在栏

我试图得到价格的平均值

import pandas as pd
df = pd.read_csv('sample_data1.csv')
#文件样本

Name,Price
Eedor,"¥1,680"
Avidlove,"¥11,761"
Fitment,
Vintage,$8.95 - $16.95
silhouette,$27.80 - $69.50
Silk,$50.02
我试图得到“价格”栏中的平均值,如果是日元兑换美元,我已经编写了这个小函数,应该可以完成这项工作,我不知道如何在栏中应用它

import re
#1¥ =0.0090$
def my_func(value):
    if not value:
        return None #remove row
    elif "¥" in value:
        try:
            temp = re.search(r'(\d+\,*\.*\d*) - .(\d+\,*\.*\d*)',value).groups()
            return (float(temp[0].replace(',',''))+float(temp[1].replace(',','')))*0.09/2
        except:
            return float(re.search(r'(\d+\,*\.*\d*)',value).groups()[0].replace(',',''))*0.009
    else:
        try:
            temp = re.search(r'(\d+\,*\.*\d*) - .(\d+\,*\.*\d*)',value).groups()
            return (temp[0]+temp[1])/2
        except:
            return float(re.search(r'(\d+\,*\.*\d*)',value).groups()[0].replace(',',''))

我想要的是将价格列替换为以美元为单位的平均值。

这是您想要的,没有货币符号:

df['average'] = df.Price.str.replace(',','').str.extractall('([\d\.]+)').astype(float)[0].mean(level=0)
输出:

         Name            Price   average
0       Eedor           ¥1,680   1680.00
1    Avidlove          ¥11,761  11761.00
2     Fitment              NaN       NaN
3     Vintage   $8.95 - $16.95     12.95
4  silhouette  $27.80 - $69.50     48.65
5        Silk           $50.02     50.02
要修正日元汇率:

df['average'] = np.where(df.Price.str[:1].eq('¥'), 
                         df['average']*Yen_to_USD_rate, 
                         df['average'])

我不知道怎样才能把它应用到专栏上你是什么意思?这是我的复制品吗?这似乎是通过阅读熊猫文档可以解决的问题。这些数据的格式看起来不一致。顺便说一句,像这样使用一个裸露的
except
语句是不好的做法,请参见,例如。@AMC我知道它只会导致
AttributeError
异常,在您提到的问题上,它是如何无关的?如果您试图捕获的错误是AttributeError,为什么不使用除AttributeError之外的
使其更安全、更明确?