简体   繁体   English

使用 pandas 遍历 df 以创建新列

[英]Iterating through a df with pandas to make new columns

I am currently trying for the first time to iterate through a set of columns (within a df) with the goal of creating a two new columns with:我目前第一次尝试遍历一组列(在 df 内),目标是创建两个新列:

1).one that totals up the number of 1's in the columns it iterated through 2).the second column if any of the iterated columns have a 1 in it, it puts a one in the new column and breaks. 1). 将迭代的列中 1 的总数加起来 2). 第二列,如果任何迭代的列中有 1,它将在新列中放入 1 并中断。 *** I solved this piece *** ***我解决了这个问题***

ADDED MY DF for context:为上下文添加了我的 DF:

   INDEX     ID    STATE Filed_Month  ...   MI   HD  Stroke  Diabeties_all
0      0  20190  Alabama     January  ...  2.0  2.0     2.0            3.0
1      1  20191  Alabama     January  ...  2.0  2.0     2.0            3.0
2      2  20192  Alabama     January  ...  2.0  2.0     2.0            1.0
3      3  20193  Alabama     January  ...  2.0  2.0     2.0            3.0
4      4  20194  Alabama     January  ...  2.0  2.0     2.0            3.0

[5 rows x 13 columns]

I also should mention when totaling up the 1's I am only interested in 7 out of the 13 columns.我还应该提到,在合计 1 时,我只对 13 列中的 7 列感兴趣。

I was able to get the second part of my question using the following:我能够使用以下内容得到问题的第二部分:

def ifanyCM(row):
    if row["Asthma"] == 1:
        return 1
    if row["Asthma"] != 1:
        return 0
    if row["COPD_all"] == 1:
        return 1
    if row["COPD_all"] != 1:
        return 0
    if row["Skin_Cancer"] == 1:
        return 1
    if row["Skin_Cancer"] != 1:
        return 0
    if row["Other_Cancer"] == 1:
        return 1
    if row["Other_Cancer"] != 1:
        return 0
    if row["MI"] == 1:
        return 1
    if row["MI"] != 1:
        return 0
    if row["HD"] == 1:
        return 1
    if row["HD"] != 1:
        return 0
    if row["Stroke"] == 1:
        return 1
    if row["Stroke"] != 1:
        return 0
    if row["Diabeties_all"] == 1:
        return 1
    if row["Diabeties_all"] != 1:
        return 0
    
y2019_r1["CM"] = y2019_r1.apply(lambda row: ifanyCM(row), axis=1) 

I am just struggling to total up the ones out of the 7 columns of interest.我只是在努力将 7 列感兴趣的列加起来。

Cheers,干杯,

Rachel雷切尔

It's unclear what your dataframe looks like.目前还不清楚您的 dataframe 是什么样的。 But assuming it's a wide dataframe like this:但假设它是这样的宽 dataframe :

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:然后你根本不需要任何循环或.apply (因为apply与循环是一回事:

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

An easy way to do it is by using a df.apply() with a lambda function in pandas.一个简单的方法是在 pandas 中使用df.apply()和 lambda function。 When you specify axis=1 it will process the a row in the dataframe as a series.当您指定 axis=1 时,它将把 dataframe 中的一行作为一个系列处理。 In the example below I counted the length of a list comprehension that only kept the 1 values in the row to count the number of 1s.在下面的示例中,我计算了列表理解的长度,该列表理解仅保留行中的 1 值来计算 1 的数量。 Subsequently I used another df.apply() to the column with the total number of 1s to check whether it contains a value larger than 0.随后我对总数为 1 的列使用了另一个 df.apply() 来检查它是否包含大于 0 的值。

import pandas as pd

l = [[1, 2, 1, 2, 7, 1],[2, 9, 2, 2, 2, 2]]
df= pd.DataFrame(l)
df['total 1s'] = df[[0,1,2,3,4,5]].apply(lambda row: len([i for i in row if i == 1]), axis=1)
df['any 1s'] = df['total 1s'].apply(lambda x: False if x == 0 else True)

Result:结果:

+----+-----+-----+-----+-----+-----+-----+------------+----------+
|    |   0 |   1 |   2 |   3 |   4 |   5 |   total 1s | any 1s   |
|----+-----+-----+-----+-----+-----+-----+------------+----------|
|  0 |   1 |   2 |   1 |   2 |   7 |   1 |          3 | True     |
|  1 |   2 |   9 |   2 |   2 |   2 |   2 |          0 | False    |
+----+-----+-----+-----+-----+-----+-----+------------+----------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM