如何计算每一行的奇数/偶数数量,并将该值放入另一列中。

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

How to count odd/even number in each row and put that value in another column

问题

我想要获取每一行中偶数和奇数的数量,并将这些值放入另一列,比如"coleven"和"colodd"。这段代码只允许我一次处理一行,而不是处理所有行。

  1. import pandas as pd
  2. import numpy as np
  3. df = pd.read_csv('allornothingev.csv')
  4. print(df)
  5. row_list = df.loc[0, :].values.flatten().tolist()
  6. # 查看结果
  7. print(row_list)
  8. count_odd = 0
  9. count_even = 0
  10. for x in row_list:
  11. if not x % 2:
  12. count_even += 1
  13. else:
  14. count_odd += 1
  15. print("偶数的数量:", count_even)
  16. print("奇数的数量:", count_odd)
英文:

I want to get the number of even/odds numbers in each row and put the value in another column such as coleven and colodd. This code only lets me do it one row at a time instead of doing it to all rows

  1. import pandas as pd
  2. import numpy as np
  3. df = pd.read_csv('allornothingev.csv')
  4. print(df)
  5. row_list = df.loc[0, :].values.flatten().tolist()
  6. #view results
  7. print(row_list)
  8. count_odd = 0
  9. count_even = 0
  10. for x in numbers:
  11. if not x % 2:
  12. count_even+=1
  13. else:
  14. count_odd+=1
  15. print("Number of even numbers :",count_even)
  16. print("Number of odd numbers :",count_odd)

答案1

得分: 1

取模运算有助于判断一个数是奇数还是偶数。

对于偶数,您可以使用 x % 2 == 0,对于奇数,可以使用 x % 2 == 1

您可以将此操作与一些逻辑结合使用,根据结果将其放入奇数或偶数列。

英文:

Modulus is helpful in finding if a number is odd or even. modulo

for an even number you can do x % 2 == 0, for odd x % 2 == 1

You can do this operation combined with some logic and depending on the result put it in a odd or even column.

答案2

得分: 1

  1. import pandas as pd
  2. import numpy as np
  3. np.random.seed(123)
  4. # 创建一个玩具数据集
  5. df = pd.DataFrame({
  6. "a": np.random.randint(0, 100, 1000),
  7. "b": np.random.randint(0, 100, 1000),
  8. "c": np.random.randint(0, 100, 1000)
  9. })
  10. # 创建列
  11. df.assign(
  12. coleven=lambda x: x.apply(lambda x: x % 2 == 0, axis=1).sum(axis=1),
  13. colodd=lambda x: x.shape[1] - x["coleven"]) # 为了避免重复操作,我只是用列数减去coleven的数量。这假定所有列都是数值型的
英文:
  1. import pandas as pd
  2. import numpy as np
  3. np.random.seed(123)
  4. # create a toy dataset
  5. df = pd.DataFrame({
  6. "a" : np.random.randint(0, 100, 1000),
  7. "b" : np.random.randint(0, 100, 1000),
  8. "c": np.random.randint(0, 100, 1000)
  9. })
  10. # create columns
  11. df.assign(
  12. coleven = lambda x: x.apply(lambda x: x % 2 == 0, axis=1).sum(axis=1),
  13. colodd = lambda x: x.shape[1] - x["coleven"]) # to save doing the same thing over again, I just do number of columns minus coleven. This is assuming all columns are numeric

huangapple
  • 本文由 发表于 2023年7月14日 01:15:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76681844.html
匿名

发表评论

匿名网友

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

确定