英文:
How to count odd/even number in each row and put that value in another column
问题
我想要获取每一行中偶数和奇数的数量,并将这些值放入另一列,比如"coleven"和"colodd"。这段代码只允许我一次处理一行,而不是处理所有行。
import pandas as pd
import numpy as np
df = pd.read_csv('allornothingev.csv')
print(df)
row_list = df.loc[0, :].values.flatten().tolist()
# 查看结果
print(row_list)
count_odd = 0
count_even = 0
for x in row_list:
if not x % 2:
count_even += 1
else:
count_odd += 1
print("偶数的数量:", count_even)
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
import pandas as pd
import numpy as np
df = pd.read_csv('allornothingev.csv')
print(df)
row_list = df.loc[0, :].values.flatten().tolist()
#view results
print(row_list)
count_odd = 0
count_even = 0
for x in numbers:
if not x % 2:
count_even+=1
else:
count_odd+=1
print("Number of even numbers :",count_even)
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
import pandas as pd
import numpy as np
np.random.seed(123)
# 创建一个玩具数据集
df = pd.DataFrame({
"a": np.random.randint(0, 100, 1000),
"b": np.random.randint(0, 100, 1000),
"c": np.random.randint(0, 100, 1000)
})
# 创建列
df.assign(
coleven=lambda x: x.apply(lambda x: x % 2 == 0, axis=1).sum(axis=1),
colodd=lambda x: x.shape[1] - x["coleven"]) # 为了避免重复操作,我只是用列数减去coleven的数量。这假定所有列都是数值型的
英文:
import pandas as pd
import numpy as np
np.random.seed(123)
# create a toy dataset
df = pd.DataFrame({
"a" : np.random.randint(0, 100, 1000),
"b" : np.random.randint(0, 100, 1000),
"c": np.random.randint(0, 100, 1000)
})
# create columns
df.assign(
coleven = lambda x: x.apply(lambda x: x % 2 == 0, axis=1).sum(axis=1),
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论