我正在遍历文件,处理一些数据以生成数组(Value1,Value2,Value3),并将它们组合成如下数据框:
df1:
ID Country Value1 Value2 Value3
BB US 3.5 6.32 1.02
BB US 6.7 2.32 5.2
BB US 9.3 4.32 4.02
BB US 4.6 5.32 4.1
df2:
ID Country Value1 Value2 Value3
BB AU 5.3 5.12 7.02
BB AU 7.12 1.32 5.02
BB AU 3.542 2.12 2.02
BB AU 2.4 5.82 6.02
df3:
ID Country Value1 Value2 Value3
BB AU 0.23 1.23 9.1
BB AU 4.567 4.46 9.2
BB AU 5.34 9.23 0.1
BB AU 9.67 6.34 2.14
所有维度均相同,并带有分类列(ID,国家/地区)。我想在循环结束时将数据帧连接为单个数据帧,但是在类别列相同的情况下(在本示例中为df2和df3),我只想将数据值最高的列保留在“ Value3'(此处为df3),得到的内容如下:
dfconcat:
ID Country Value1 Value2 Value3
BB US 3.5 6.32 1.02
BB US 6.7 2.32 5.2
BB US 9.3 4.32 4.02
BB US 4.6 5.32 4.1
BB AU 0.23 1.23 9.1
BB AU 4.567 4.46 9.2
BB AU 5.34 9.23 0.1
BB AU 9.67 6.34 2.14
我知道如何连接的dataframes,我觉得剩下的可以用做np.where
和.apply
,但不能弄明白。
用途concat
:
L = [df1, df2, df3]
df = pd.concat([x.assign(max1 = x['Value3'].max()) for x in L])
df = df[df.groupby(['ID','Country'])['max1'].transform('max').eq(df['max1'])]
print (df)
ID Country Value1 Value2 Value3 max1
0 BB US 3.500 6.32 1.02 5.2
1 BB US 6.700 2.32 5.20 5.2
2 BB US 9.300 4.32 4.02 5.2
3 BB US 4.600 5.32 4.10 5.2
0 BB AU 0.230 1.23 9.10 9.2
1 BB AU 4.567 4.46 9.20 9.2
2 BB AU 5.340 9.23 0.10 9.2
3 BB AU 9.670 6.34 2.14 9.2
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句