Issue
I have a pandas dataframe and I'm trying to change the values in a given column which are represented by strings into integers. For instance:
df = index fruit quantity price
0 apple 5 0.99
1 apple 2 0.99
2 orange 4 0.89
4 banana 1 1.64
...
10023 kiwi 10 0.92
I would like it to look at:
df = index fruit quantity price
0 1 5 0.99
1 1 2 0.99
2 2 4 0.89
4 3 1 1.64
...
10023 5 10 0.92
I can do this using
df["fruit"] = df["fruit"].map({"apple": 1, "orange": 2,...})
which works if I have a small list to change, but I'm looking at a column with over 500 different labels. Is there any way of changing this from a string
to a an int
?
Solution
Use factorize
and then convert to categorical
if necessary:
df.fruit = pd.factorize(df.fruit)[0]
print (df)
fruit quantity price
0 0 5 0.99
1 0 2 0.99
2 1 4 0.89
3 2 1 1.64
4 3 10 0.92
df.fruit = pd.Categorical(pd.factorize(df.fruit)[0])
print (df)
fruit quantity price
0 0 5 0.99
1 0 2 0.99
2 1 4 0.89
3 2 1 1.64
4 3 10 0.92
print (df.dtypes)
fruit category
quantity int64
price float64
dtype: object
Also if need count from 1
:
df.fruit = pd.Categorical(pd.factorize(df.fruit)[0] + 1)
print (df)
fruit quantity price
0 1 5 0.99
1 1 2 0.99
2 2 4 0.89
3 3 1 1.64
4 4 10 0.92
Answered By - jezrael
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.