如何根据条件对数据框的所有列进行乘法操作?

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

How to multiply all columns of a dataframe based on a condition?

问题

我想将数据框中小于1的所有值乘以1000。
以下是数据框的示例:
如何根据条件对数据框的所有列进行乘法操作?

感谢您的帮助。

英文:

I want to multiply all values less than 1 in a dataframe by 1000.
Below is an example of a dataframe;
如何根据条件对数据框的所有列进行乘法操作?

Appreciate your help.

答案1

得分: 1

  1. for col in df.columns.tolist():
  2. df[col] = df[col].apply(lambda x: x * 1000 if x < 1 else x, axis=1)
英文:
  1. for col in df.columns.tolist()
  2. df[col] = df[col].apply(lambda x: x * 1000 if x &lt; 1, axis=1)

答案2

得分: 1

如果第一列不是数字,请使用DataFrame.iloc选择除第一列以外的所有列,并根据条件使用numpy.where将它们乘以10001

  1. df = pd.DataFrame({
  2. 'A':list('abc'),
  3. 'B':[4,-5,4],
  4. 'C':[7,8,-9],
  5. 'D':[7,1,0]})
  6. df.iloc[:, 1:] *= np.where(df.iloc[:, 1:] < 1, 1000, 1)
  7. print (df)
  8. A B C D
  9. 0 a 4 7 7
  10. 1 b -5000 8 1
  11. 2 c 4 -9000 0

如果第一列是索引,请根据条件将所有列都乘以相应的值:

  1. df = pd.DataFrame({
  2. 'B':[4,-5,4],
  3. 'C':[7,8,-9],
  4. 'D':[7,1,0]}, index=list('abc'))
  5. df[df < 1] *= 1000
  6. #print (df)
  7. #输出:
  8. # B C D
  9. #a 4 7 7
  10. #b -5000 8 1
  11. #c 4 -9000 0

请注意,上述代码中的中文部分已经翻译完成,代码部分没有翻译。

英文:

If first column is not numeric use multiple all columns without first selected by DataFrame.iloc by 1000 or 1 by condition with numpy.where:

  1. df = pd.DataFrame({
  2. &#39;A&#39;:list(&#39;abc&#39;),
  3. &#39;B&#39;:[4,-5,4],
  4. &#39;C&#39;:[7,8,-9],
  5. &#39;D&#39;:[7,1,0]})
  6. df.iloc[:, 1:] *= np.where(df.iloc[:, 1:] &lt; 1, 1000, 1)
  7. print (df)
  8. A B C D
  9. 0 a 4 7 7
  10. 1 b -5000 8 1
  11. 2 c 4 -9000 0

If first column is index multiple all columns by condition:

  1. df = pd.DataFrame({
  2. &#39;B&#39;:[4,-5,4],
  3. &#39;C&#39;:[7,8,-9],
  4. &#39;D&#39;:[7,1,0]}, index=list(&#39;abc&#39;))
  5. df[df &lt; 1] *= 1000
  6. #same like
  7. #df[df &lt; 1] = df[df &lt; 1] * 1000
  8. print (df)
  9. B C D
  10. a 4 7 7
  11. b -5000 8 1
  12. c 4 -9000 0

huangapple
  • 本文由 发表于 2020年1月3日 15:21:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574642.html
匿名

发表评论

匿名网友

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

确定