Pandas: Increment Column Value by 1
Pandas is a powerful library in Python used for data manipulation and analysis. To increment a column value by 1 in a pandas DataFrame, you can use either the +=
operator or the add()
method.
Here is an example to demonstrate both methods:
import pandas as pd
# Create a DataFrame
data = {'A': [1, 2, 3, 4]}
df = pd.DataFrame(data)
# Method 1: Using +=
df['A'] += 1
# Method 2: Using add()
df['A'] = df['A'].add(1)
# Print the updated DataFrame
print(df)
The above code creates a DataFrame with a column ‘A’ containing numbers 1, 2, 3, and 4. Using both methods, we increment each value by 1.
The output of the code will be:
A
0 2
1 3
2 4
3 5
As you can see, both methods update the ‘A’ column values by incrementing them by 1.