遍历数据框中的每一行和每一列并对列值执行操作

时间:2021-03-15 02:27:21

标签: python pandas dataframe loops for-loop

我有一个如下所示的 DataFrame,我想创建一个新列“Six”,以便该列的值取决于“Second”、“Third”、“Forth”、“Fifth”列值的值。如果 value = 1,则附加到 First 列的值,如果 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

1 个答案:

答案 0 :(得分:4)

让我们试试这个:

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