It's unclear what your dataframe looks like. But assuming it's a wide dataframe like this:
import pandas
import numpy
df = pandas.DataFrame({
1: [1, 2, 1, 2, 7, 1, 1, 9],
2: [2, 9, 2, 2, 2, 1, numpy.nan, numpy.nan]
}).fillna(0).astype(int).T.rename(
index=lambda r: f"row{r}",
columns=lambda r: f"col{r}",
)
col0 col1 col2 col3 col4 col5 col6 col7
row1 1 2 1 2 7 1 1 9
row2 2 9 2 2 2 1 0 0
Then you don't need any loops or .apply
at all (because apply
is the same thing as a loop:
data = df.assign(
CountOfOnes=lambda df: df.eq(1).sum(axis=1),
HasAnyOne=lambda df: df.eq(1).any(axis=1)
)
Which is:
col0 col1 col2 col3 col4 col5 col6 col7 CountOfOnes HasAnyOne
row1 1 2 1 2 7 1 1 9 4 True
row2 2 9 2 2 2 1 0 0 1 True
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…