Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

python - Pandas DataFrame: apply function to all columns

I can use .map(func) on any column in a df, like:

df=DataFrame({'a':[1,2,3,4,5,6],'b':[2,3,4,5,6,7]})

df['a']=df['a'].map(lambda x: x > 1)

I could also:

df['a'],df['b']=df['a'].map(lambda x: x > 1),df['b'].map(lambda x: x > 1)

Is there a more pythonic way to apply a function to all columns or the entire frame (without a loop)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I understand you right, you're looking for the applymap method.

>>> print df
   A  B  C
0 -1  0  0
1 -4  3 -1
2 -1  0  2
3  0  3  2
4  1 -1  0
>>> print df.applymap(lambda x: x>1)
       A      B      C
0  False  False  False
1  False   True  False
2  False  False   True
3  False   True   True
4  False  False  False

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...