python - 将 Pandas 数据框的多列与具有不同长度和索引的另一个数据框的一列进行比较

标签 python pandas dataframe

我有数据框 dd1:

     A   B   C  D    E  
  0  V  10   5  18  20       
  1  W   9  18  11  13      
  2  X   8   7  12   5      
  3  Y   7   9   7   8       
  4  Z   6   5   3  90       

我想在 dd1 中添加一个“结果”列,如果“E”列中的值大于 dd1 列 A、B、C 和 D 中的值,则该列应返回零,否则返回大于 dd1 列 E 的值

   A   B   C   D   E  Result
0  V  10   5  18  20       0
1  W   9  18  11  13      18
2  X   8   7  12   5      12
3  Y   7   9   7   8       9
4  Z   6   5   3  90       0

最佳答案

可以通过DataFrame.lt进行比较按位置选择的列 DataFrame.iloc或列名列表,通过 DataFrame.all 检查每行是否所有 True并通过 numpy.where 设置值到新专栏:

df1 = df.iloc[:, 1:-1]
#for select by columns names
#df1 = df[['B','C','D']]
df['Result'] = np.where(df1.lt(df['E'], axis=0).all(axis=1), 0, df1.max(axis=1))

另一个想法是比较 Series.gt每个选定列的最大值,然后乘以 Series.mul :

s = df.iloc[:, 1:-1].max(axis=1)
df['Result'] = s.gt(df['E']).mul(s)
print (df)
   A   B   C   D   E  Result
0  V  10   5  18  20       0
1  W   9  18  11  13      18
2  X   8   7  12   5      12
3  Y   7   9   7   8       9
4  Z   6   5   3  90       0

关于python - 将 Pandas 数据框的多列与具有不同长度和索引的另一个数据框的一列进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56089640/

相关文章:

python - 在 Python 中修复深度树

r - 使用 dplyr 和 add_row() 在每个组中添加行

python - 通过代理连接发送带有 header 的 aiohttp post 请求

python - Kivy:如何检索在 python 中创建的复选框(或其他小部件)的 ID 或事件状态

python - 从真值表 pandas 中提取数据

python - Pandas 图 : scatter plot with index

python - 比较 bool 系列

python - 通过切片索引和条件行设置值

python pandas.Series.str.包含带空格的单词

python - 如何评估 lambda 函数的多个值?