一次更改每一行

9udxz4iz  于 2021-09-08  发布在  Java
关注(0)|答案(3)|浏览(154)

我有一个 Dataframe df,它有以下列

A   B   C   D
06/09/2019   56 67  33  10
06/10/2019   54 66  47  23
06/11/2019   67 1   43  19
06/12/2019   21 38  8   71

我有两个 Dataframe ,有下限(l)和上限(u)
下切角:

l   
06/09/2019   20 
06/10/2019   12  
06/11/2019   10   
06/12/2019   15

上东区:

u 
06/09/2019   60
06/10/2019   70  
06/11/2019   55  
06/12/2019   50

我想使用两个 Dataframe (下_df和上_df)的值作为条件,将第一个 Dataframe (df)列的值更新为0。在这里,每一行都是孤立的,每一列都与相应的u&l值进行比较。小于l和大于u的值设置为零。
所需结果:

A   B   C   D
06/09/2019   56  0  33  0
06/10/2019   54 66  47  23
06/11/2019   0  0   43  19
06/12/2019   21 38   0  0

我使用以下代码从dataframe中提取每一行,并将列与此上限和下限进行比较:

for i in range(0,len(df)):
  ul=upper_df.iloc[i]
  ll=lower_df.iloc[i]
  df.iloc[i][df.iloc[i]<ll[0]]=0
  df.iloc[i][df.iloc[i]>ul[0]]=0

但这并没有反映出任何变化,df保持原样。代码正确吗?如果没有,正确的方法是什么。这个数据集是巨大的(很多列,这是一个例子),我正在寻找一个更聪明的方法来做到这一点。

enxuqcxy

enxuqcxy1#

使用 DataFrame.mask 与相比 DataFrame.ltDataFrame.gt 被束缚 | 按位计算 OR :

df = df.mask(df.lt(lower_df['l'], axis=0) | df.gt(upper_df['u'], axis=0), 0)
print (df)
             A   B   C   D
06/09/2019  56   0  33   0
06/10/2019  54  66  47  23
06/11/2019   0   0  43  19
06/12/2019  21  38   0   0
5sxhfpxr

5sxhfpxr2#

iiuc,还有另一种方法:

df = df.mul((lower_df.values < df.values) & (
    df.values < upper_df.values).astype(int))

输出:

A   B   C   D
06/09/2019  56   0  33   0
06/10/2019  54  66  47  23
06/11/2019   0   0  43  19
06/12/2019  21  38   0   0
iyfamqjs

iyfamqjs3#

这是因为您没有将它们保存到df。另外,还有一个简洁的numpy函数np.where(),请参见https://numpy.org/doc/1.20/reference/generated/numpy.where.html.

for i in range(0,len(df)):
  ul=upper_df.iloc[i]
  ll=lower_df.iloc[i]
  df.loc[i] = np.where(np.logical_or(df.loc[i] <= ll, df.loc[i] >= ul), 0, df.loc[i])

相关问题