简体   繁体   English

CSV行与Python的比较

[英]Comparison of CSV rows with Python

I sorted my CSV file to make some calculates. 我对CSV文件进行了排序以进行一些计算。 Python 2.7 Python 2.7

import pandas as pd
df = pd.read_csv('Cliente_x_Pais_Sitio.csv', sep=',')
df1 = df.sort_values(by=['Cliente','Auth_domain','Sitio',"Country"])
df1.to_csv('test.csv')

CSV data ( test.csv ): CSV数据( test.csv ):

Cliente,Fecha,Auth_domain,Sitio,Country,ECPM_medio
FF,15/12/2017,@ff,ff_Color,Afganistán,0.53
FF,15/01/2018,@ff,ff_Color,Afganistán,0.5
FF,15/01/2017,@ff,ff_Color,Alemania,0.34
FF,15/12/2017,@ff,ff_Color,Alemania,0.38
FF,15/01/2018,@ff,ff_Color,Alemania,0.37

What I need: 我需要的:

if (15/12/2017 ECPM) ≤ (15/01/2018 ECPM):
    if ((15/12/2017 ECPM)*0.8) ≥ (15/01/2017 ECPM):
        r = (15/01/2017 ECPM)
    else:
        r = ((15/12/2017 ECPM)*0.8)
else:
    if (15/01/2018 ECPM) ≥ (15/01/2017 ECPM):
        r = (15/01/2017 ECPM)
    else:
        r = (15/01/2018 ECPM)

Filling in the real data, the first two lines would be: 填写实际数据,前两行为:

if 0.53 ≤ 0.5:
    if 0.5 ≥ 0: #if we don't have the cell value I would like to add a 0 True
        r = 0.5

Remember I have more than 10,000 rows son I need a multiple form 请记住,我有10,000多行,我需要多种形式

The new CSV should show me this: 新的CSV应该显示以下内容:

Cliente,Auth_domain,Sitio,Country,Recomendation_ECPM
FF,@ff,ff_Color,Afganistán,0.5
FF,@ff,ff_Color,Alemania,0.34

I'm not sure I have the correct 我不确定我是否正确

  1. date selection in setval or setval日期选择或
  2. the return value logic in compare_val compare_val的返回值逻辑

But the pipeline regardless of those uses sort, group_by, and transform. 但是,无论使用哪种管道,都使用sort,group_by和transform。 Because we'll compare the edges to nan ( shift(-1) on first, and shift(1) on the end), we have to remove them at the end. 因为我们将边缘与nan (首先是shift(-1) ,最后是shift(1) )进行比较,所以我们必须在最后删除它们。

# build data
from StringIO import StringIO
import pandas as pd
df = pd.read_csv(StringIO("""Cliente,Fecha,Auth_domain,Sitio,Country,ECPM_medio
FF,15/12/2017,@ff,ff_Color,Afganistán,0.53
FF,15/01/2018,@ff,ff_Color,Afganistán,0.5
FF,15/01/2017,@ff,ff_Color,Alemania,0.34
FF,15/12/2017,@ff,ff_Color,Alemania,0.38
FF,15/01/2018,@ff,ff_Color,Alemania,0.37
""")).sort_values(by='Fecha')

# functions to parse
def compare_val(cur,past,future):
   if cur <= past:
       cur_adj = cur * .8
       if cur_adj >= past:
            return(past)
       else:
            return(cur_adj)
   else:
        if future >= past:
           return(past)
        else:
           return(future)

def setval(v):
      cur, past, future = v, v.shift(-1), v.shift(1)
      v = [ compare_val(*x) for x in zip(cur,past,future)]
      return(v)

# do the work
df['Recomendation_ECPM'] = df.\
      groupby(['Cliente','Auth_domain','Sitio',"Country"])['ECPM_medio'].\
      transform(setval)

df[ pd.notna(df['Recomendation_ECPM']) ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM