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

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

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

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

答案2

得分: 1

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

df = pd.DataFrame({
        'A':list('abc'),
         'B':[4,-5,4],
         'C':[7,8,-9],
         'D':[7,1,0]})

df.iloc[:, 1:] *= np.where(df.iloc[:, 1:] < 1, 1000, 1)
print (df)
   A     B     C  D
0  a     4     7  7
1  b -5000     8  1
2  c     4 -9000  0

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

df = pd.DataFrame({
         'B':[4,-5,4],
         'C':[7,8,-9],
         'D':[7,1,0]}, index=list('abc'))

df[df < 1] *= 1000
#print (df)
#输出:
#       B     C  D
#a     4     7  7
#b -5000     8  1
#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:

df = pd.DataFrame({
        &#39;A&#39;:list(&#39;abc&#39;),
         &#39;B&#39;:[4,-5,4],
         &#39;C&#39;:[7,8,-9],
         &#39;D&#39;:[7,1,0]})

df.iloc[:, 1:] *= np.where(df.iloc[:, 1:] &lt; 1, 1000, 1)
print (df)
   A     B     C  D
0  a     4     7  7
1  b -5000     8  1
2  c     4 -9000  0

If first column is index multiple all columns by condition:

df = pd.DataFrame({
         &#39;B&#39;:[4,-5,4],
         &#39;C&#39;:[7,8,-9],
         &#39;D&#39;:[7,1,0]}, index=list(&#39;abc&#39;))

df[df &lt; 1] *= 1000
#same like
#df[df &lt; 1] = df[df &lt; 1] * 1000
print (df)
      B     C  D
a     4     7  7
b -5000     8  1
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:

确定