How to Create Bins Dataframe in Python
To create bins dataframe in Python, you can use the pd.cut() function from the pandas library.
The following example shows how to create bins in a dataframe in Python using the pd.cut() function.
Using pd.cut() Function
We can use the pd.cut() function to create bins in a dataframe.
Let’s see how to use the pd.cut() function in Python:
# Import pandas library
import pandas as pd
# Create dataframe
office_stuff = pd.DataFrame({
'Product_Code': ['101', '102', '103', '104', '105', '106'],
'Price': [4500, 550, 250, 50, 350, 50],
'Status': [1, 1, 1, 0, 1, 1]
})
# Create bins
office_stuff['bins'] = pd.cut(office_stuff['Price'], bins=2)
# Print dataframe
print(office_stuff)
Output: 👇️
Product_Code Price Status bins
0 101 4500 1 (2275.0, 4500.0]
1 102 550 1 (45.55, 2275.0]
2 103 250 1 (45.55, 2275.0]
3 104 50 0 (45.55, 2275.0]
4 105 350 1 (45.55, 2275.0]
5 106 50 1 (45.55, 2275.0]
In this example, we use the pd.cut() function to create bins in the Price column of the dataframe office_stuff.
The output shows the updated dataframe with the bins added to it.
Conclusion
We can use the pd.cut() function from the pandas library to create bins in a dataframe in Python.