file_name expression
0 test_0000.jpg1
1 test_0001.jpg0
2test_0002.jpg0
3test_0003.jpg0
4test_0004.jpg2
... ... ...
307test_0307.jpg1
308test_0308.jpg0
309test_0309.jpg1
310 test_0310.jpg3
311 test_0311.jpg1
The number in the expression
line of this dataframe is
0
< neutral
1
< happy
2
< sad
3
< angry
I wanted to convert it to , so I implemented the code below.
Submit ['expression'].replace({'0': 'neutral', '1': 'happy', '2': 'sad', '3': 'angry'})
This error has occurred.
TypeError: Cannot compare types'ndarray(dtype=uint8)' and 'str'
I tried the following, but
1.Convert to str at replace
Submit['expression'].replace(str.maketrans({'0':'neutral','1':'happy','2':'sad','3':'angry'}))
2. Convert numeric rows to strings when creating dataframe
Submit1=Submit['expression'].astype(str)
There was an error and I could not convert it.
I would appreciate your advice on this error.
Thank you for your cooperation.
The conversion dictionary has been used as a numeric key and as a string.
Both are available
import pandas as pd
df = pd.DataFrame([
['test_0000.jpg',1],
['test_0001.jpg',0',
['test_0002.jpg',0',
['test_0003.jpg',0',
['test_0004.jpg',2',columns=['file_name','expression')]
dct_int = {0:'neutral', 1:'happy', 2:'sad', 3:'angry'}
dct_str = {'0': 'neutral', '1': 'happy', '2': 'sad', '3': 'angry'}
df['exp_name'] = df['expression'].replace(dct_int)
df['exp_name2'] = df['expression'].astype(str).replace(dct_str)
display(df)
What you have tried (1) is not appropriate for the dictionary given to replace
, and the conversion will fail.
I don't know what went wrong with what I tried (2)
df is the following DataFrame.
file_name expression
0 test_0000.jpg1
1 test_0001.jpg0
2test_0002.jpg0
3test_0003.jpg0
4test_0004.jpg2
5test_0307.jpg1
6test_0308.jpg0
7test_0309.jpg1
8test_0310.jpg3
9test_0311.jpg1
You can convert and replace the expression column type.
df['expression'] = df['expression'].astype(str)
df['expression'] = df['expression'].replace({'0': 'neutral', '1': 'happy', '2': 'sad', '3': 'angry'})
print(df)
# file_name expression
#0 test_0000.jpg happy
#1 test_0001.jpg neutral
#2 test_0002.jpg neutral
#3 test_0003.jpg neutral
#4 test_0004.jpg sad
#5 test_0307.jpg happy
#6 test_0308.jpg neutral
#7test_0309.jpg happy
#8 test_0310.jpg angry
#9test_0311.jpg happy
© 2024 OneMinuteCode. All rights reserved.