使用Pandas根据另一列的条件重置列的值

huangapple go评论50阅读模式
英文:

Reset values of a column based on conditions from another column Pandas

问题

我有一个包含'时间'和'Col1'列的DataFrame。我想编写一个简单的函数,用于在'Time'列中的时间间隔内更改'Col1'的值。

我不知道为什么以下代码会产生以下错误:

ValueError: Series的真值是模棱两可的。请使用a.empty,a.bool(),a.item(),a.any()或a.all()。

val = 5
time1 = 200
time2 = 300
def reset_value(df, val, time1, time2):
   df.loc[(df['Time'] >= time1) & (df['Time'] < time2), 'Col1'] = val
   return df

如果您有其他需要,请随时告诉我。

英文:

I have df with columns 'Time' and 'Col1'. I would like to write a simple function that changes the values of 'Col1' between the time intervals from 'Time' column.

I don't know why the following code produces the following error:

> ValueError: The truth value of a Series is ambiguous. Use a.empty,
> a.bool(), a.item(), a.any() or a.all().

val = 5
time1 = 200
time2 = 300
def reset_value(df, val, time1, time2):
   df.loc[df[&#39;Time&#39;] &gt;= time1 and df[&#39;Time&#39;]&lt;time2, &#39;Col1&#39;] = val
   return df

答案1

得分: 0

使用 &amp; 用于位运算 AND 并添加括号:

df.loc[(df['Time'] &gt;= time1) &amp; (df['Time']&lt;time2), 'Col1'] = val

或者使用 Series.geSeries.lt

df.loc[df['Time'].ge(time1) &amp; df['Time'].lt(time2), 'Col1'] = val
英文:

Use &amp; for bitwise AND and add parentheses:

df.loc[(df[&#39;Time&#39;] &gt;= time1) &amp; (df[&#39;Time&#39;]&lt;time2), &#39;Col1&#39;] = val

Or use Series.ge and Series.lt:

df.loc[df[&#39;Time&#39;].ge(time1) &amp; df[&#39;Time&#39;].lt(time2), &#39;Col1&#39;] = val

huangapple
  • 本文由 发表于 2023年2月14日 18:51:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75446791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定