How do I add a column to a df that was created with pd.cut?
s = pd.Series(np.arange(10))
df = pd.cut(s, [-5, 0, 5, 10] )
df["Frequency"] = pd.Series(np.arange(10))
df
The output is attached however I would want C to be added to the existing df to the right as a column not at the bottom?
| index | interval | Frequency |
|---|---|---|
| One | (2 -3] | Three |
>Solution :
What you call df is actually a Series, you can convert using to_frame:
df = pd.cut(s, [-5, 0, 5, 10] ).to_frame(name='bin')
df["Frequency"] = np.arange(10)
Or directly use the DataFrame constructor:
df = pd.DataFrame({'bin': pd.cut(s, [-5, 0, 5, 10]),
'Frequency': np.arange(10)
})
Output:
bin Frequency
0 (-5, 0] 0
1 (0, 5] 1
2 (0, 5] 2
3 (0, 5] 3
4 (0, 5] 4
5 (0, 5] 5
6 (5, 10] 6
7 (5, 10] 7
8 (5, 10] 8
9 (5, 10] 9
