我有一个包含多个列的数据框,并且我只想根据某些条件将“ Views”列的最大值替换为三个不同的列。
import pandas as PD
data = [["1.Blend Of Vdx Display","DISPLAY","Features","CPE",1255,778732,13373,7142],["1.Blend Of Vdx Display","DISPLAY","TVC","CPE",10479,778732,13373,7142],
["2.Mobile VDX","Display","Features","CPE",168,1000,150,160],["2.Mobile VDX","Display","Features","CPE",2309,1000,150,160]]
df = pd.DataFrame(data,columns=['Placement#Name','PRODUCT','VIDEONAME','COST_TYPE',views','IMPRESSIONS','ENGAGEMENTS','DPEENGAMENTS'])
print(df)
Placement#Name PRODUCT VIDEONAME COST_TYPE views IMPRESSIONS \
0 1.Blend Of Vdx Display DISPLAY Features CPE 1255 778732
1 1.Blend Of Vdx Display DISPLAY TVC CPE 10479 778732
2 2.Mobile VDX DISPLAY Features CPE 168 1000
3 2.Mobile VDX DISPLAY Features CPE 2309 1000
ENGAGEMENTS DPEENGAMENTS
0 13373 7142
1 13373 7142
2 150 160
3 150 160
我可以通过这样做过滤出最大值
newdf = df.loc[df.reset_index().groupby(['Placement#Name'])['Views'].idxmax()]
print (newdf)
Placement#Name PRODUCT VIDEONAME COST_TYPE Views IMPRESSIONS \
1 1.Blend Of Vdx Display DISPLAY TVC CPE 10479 778732
3 2.Mobile VDX DISPLAY Features CPE 2309 1000
ENGAGEMENTS DPEENGAMENTS
1 13373 7142
3 150 160
现在我想用10479和2309之类的条件替换newdf视图,可以用“参与度”列替换,因为条件是显示产品,而Cost_Type是CPE。
所以新的df输出是
print (newdf)
Placement#Name PRODUCT VIDEONAME COST_TYPE Views IMPRESSIONS \
1 1.Blend Of Vdx Display DISPLAY TVC CPE 13373 778732
3 2.Mobile VDX DISPLAY Features CPE 150 1000
ENGAGEMENTS DPEENGAMENTS
1 13373 7142
3 150 160
然后我想将其转换为原始df。因此原始输出为:
print (df)
Placement#Name PRODUCT VIDEONAME COST_TYPE views IMPRESSIONS \
0 1.Blend Of Vdx Display DISPLAY Features CPE 1255 778732
1 1.Blend Of Vdx Display DISPLAY TVC CPE 13373 778732
2 2.Mobile VDX DISPLAY Features CPE 168 1000
3 2.Mobile VDX DISPLAY Features CPE 150 1000
ENGAGEMENTS DPEENGAMENTS
0 13373 7142
1 13373 7142
2 150 160
3 150 160
另一种方法-
这会过滤掉并替换特定案例,从views
至ENGAGEMENTS
newdf['views'] = newdf.apply(lambda x: x['ENGAGEMENTS'] if ((x['PRODUCT'].upper()=='DISPLAY') & (x['COST_TYPE']=='CPE')) else x['views'], axis=1)
追加2个数据框
df['views'].update(newdf['views'])
输出量
Placement#Name PRODUCT VIDEONAME COST_TYPE views IMPRESSIONS \
0 1.Blend Of Vdx Display DISPLAY Features CPE 1255 778732
1 1.Blend Of Vdx Display DISPLAY TVC CPE 13373 778732
2 2.Mobile VDX Display Features CPE 168 1000
3 2.Mobile VDX Display Features CPE 150 1000
ENGAGEMENTS DPEENGAMENTS
0 13373 7142
1 13373 7142
2 150 160
3 150 160
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句