+4 votes
in Programming Languages by (54.6k points)
Which function should I use to add a number to all elements of a Pandas DataFrame?

1 Answer

+1 vote
by (347k points)
selected by
 
Best answer

You can use the add() function of Pandas DataFrame to add any value to all elements of a DataFrame.

Here is an example:

>>> import pandas as pd
>>> df = pd.DataFrame({'a':[10,20,30], 'b':[11,22,33], 'c':[12,24,36]})
>>> df
    a   b   c
0  10  11  12
1  20  22  24
2  30  33  36

>>> df.add(5)
    a   b   c
0  15  16  17
1  25  27  29
2  35  38  41
>>> 

You can also add the number directly to the DataFrame.

Example:

>>> df+5
    a   b   c
0  15  16  17
1  25  27  29
2  35  38  41


...