首页 > 解决方案 > 遍历数据框中的每一行和每一列并对列值执行操作

问题描述

我有一个如下的 DataFrame,我想创建一个新列“Six”,这样该列的值取决于“Second”、“Third”、“Forth”、“Fifth”列值的值。如果 value = 1,则追加到第一列的值,如果 value = 0,则不执行任何操作。我可以知道怎么做吗?

Input : 

    First    Second     Third      Forth      Fifth
0   S1       1          0          0          0
1   S2       1          1          0          0
2   S3       1          1          0          0

Expected output

    First    Second     Third      Forth      Fifth    Six
0   S1       1          1          1          0        S1111
1   S2       1          1          0          0        S211
2   S3       1          1          1          0        S3111

标签: pythonpandasdataframeloopsfor-loop

解决方案


让我们试试这个:

df['Six'] = df.replace({1:'1', 0:''}).apply(''.join, axis=1)

输出:

    First   Second  Third   Forth   Fifth   Six
0   S1         1       0       0       0    S11
1   S2         1       1       0       0    S211
2   S3         1       1       0       0    S311

推荐阅读