如何在数据框某些行的所有列上使用 pandas 应用功能 [英] How to use pandas apply function on all columns of some rows of data frame
本文介绍了如何在数据框某些行的所有列上使用 pandas 应用功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个dataframe
.我想将某些行的所有列的值替换为默认值.有没有一种方法可以通过pandas apply
函数
I have a dataframe
. I want to replace values of all columns of some rows to a default value. Is there a way to do this via pandas apply
function
这是数据框
import pandas as pd
temp=pd.DataFrame({'a':[1,2,3,4,5,6],'b':[2,3,4,5,6,7],'c':['p','q','r','s','t','u']})
mylist=['p','t']
如何将列a
和b
中的值替换为默认值0,其中列c
的值位于mylist
How to replace values in columns a
and b
to default value 0,where value of column c
is in mylist
有没有一种方法可以使用熊猫功能来避免循环
Is there a way to do this using pandas functionality,avoiding for loops
推荐答案
使用 isin
创建一个布尔掩码,并使用loc
将满足条件的行设置为所需的新值:
Use isin
to create a boolean mask and use loc
to set the rows that meet the condition to the desired new value:
In [37]:
temp.loc[temp['c'].isin(mylist),['a','b']] = 0
temp
Out[37]:
a b c
0 0 0 p
1 2 3 q
2 3 4 r
3 4 5 s
4 0 0 t
5 6 7 u
内部isin
的结果:
In [38]:
temp['c'].isin(mylist)
Out[38]:
0 True
1 False
2 False
3 False
4 True
5 False
Name: c, dtype: bool
这篇关于如何在数据框某些行的所有列上使用 pandas 应用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文