【问题标题】:Iterate two pandas DataFrame rows for new hybrid values为新的混合值迭代两个 pandas DataFrame 行
【发布时间】:2020-02-26 23:53:00
【问题描述】:

我有两个具有相同列名的 pandas 数据框,并且数据与每个数据框中的不同产品类型相关。 例如,两者看起来像这样,但长度不等。

df1

Name    ScoreX ScoreY   ScoreZ
Type1   0.6     0.2      0.7
Type2   0.6     0.5      0.6
Type3   0.7     0.2      0.3
Type4   1.0     0.2      0.3

df2

Name    ScoreX ScoreY   ScoreZ
TypeA   0.5     0.1      0.9
TypeB   0.3     0.5      0.6
TypeC   0.7     0.8      0.2
TypeD   1.0     0.2      0.3

我正在尝试创建每种类型的新混合值,将 df1 中的每个产品与 df2 结合起来,并且分数值是两种产品单独分数的平均值。寻找一种迭代两个帧的方法,以便将 df1 的第一行与 df2 中的每一行组合,然后在 df1 中对每一行再次重复此过程。 所以输出在新的 df 中看起来像这样:

Name        MeanScoreX MeanScoreY MeanScoreZ
Type1_TypeA  0.55       0.15      0.8
Type1_TypeB  0.45       0.35      0.65

.......

Type2_TypeA  0.55       0.3       0.75
Type2_TypeB  0.45       0.5       0.6

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

重命名 df2 的列

df2.columns = ['Name2', 'ScoreX2' , 'ScoreY2', 'ScoreZ2']

连接两个数据帧

df = pd.concat([df1, df2], axis=1)

生成派生字段

df['Name'] = df['Name'] + df['Name2']
df['MeanScoreX'] = df[['ScoreX', 'ScoreX2']].mean(axis=1)
df['MeanScoreY'] = df[['ScoreY', 'ScoreY2']].mean(axis=1)
df['MeanScoreZ'] = df[['ScoreZ', 'ScoreZ2']].mean(axis=1)

【讨论】:

  • 谢谢@MayowaAyodele - 你的回答有助于朝着正确的方向前进
猜你喜欢
  • 1970-01-01
  • 2018-03-23
  • 2013-09-02
  • 2018-08-03
  • 2018-11-09
  • 2019-04-17
  • 1970-01-01
  • 2020-01-03
  • 2021-12-28
相关资源
最近更新 更多