替换熊猫中的多个列值

时间:2019-01-03 12:31:00

标签: python pandas

我知道如何替换数据框中的列值

df.loc[df.column_name >= value,'column_name'] = value

我的数据框看起来像这样

col1	col2	col3	upto col1000
1	2	1	1
0	3	1	1
0	1	0	1
1	1	0	0
2	1	2	2
1	0	2	2
2	0	4	4
2	2	1	4
1	2	1	2
我想将大于1的列中的所有值替换为1,并将其替换为1。是否有更简单的方法做到这一点?或者我们需要为此编写for循环?

2 个答案:

答案 0 :(得分:0)

尝试:

df.loc[:,column_name] = np.where(df.column_name > 1, 1, df.column_name)

我猜您想在列中输入0和1,或者您可以这样做:

df.loc[:,column_name] = np.where(df.column_name !=0, 1, 0)

答案 1 :(得分:0)

如何使用lambda函数和np.where()?

df = df.apply(lambda x: np.where(x > 1, 1, x))

原始数据框:

   col1  col2  col3  col1000
0     1     2     1        1
1     0     3     1        1
2     0     1     0        1
3     1     1     0        0
4     2     1     2        2
5     1     0     2        2
6     2     0     4        4
7     2     2     1        4
8     1     2     1        2

使用lambda函数后:

   col1  col2  col3  col1000
0     1     1     1        1
1     0     1     1        1
2     0     1     0        1
3     1     1     0        0
4     1     1     1        1
5     1     0     1        1
6     1     0     1        1
7     1     1     1        1
8     1     1     1        1
相关问题