The Pandas Series str function encode() used to encode character string in the Series or Index using indicated encoding. It returns either Series or Index that includes encoded string of each elements.
1 Series.str.encode(encoding, errors = 'strict')
string : A source string to encode using specified values.
encoding : It specifies the encoding on the basis of which decoding has to be performed. ie. utf-8, ascii etc.
errors : An specifies the error method, if error occurs, Optional
1. | backslashreplace : it uses a backslash instead of the character that could not be encoded. |
2. | ignore : it ignores the characters that can not be encoded. |
3. | namereplace : It replaces the character with a text explaining the character. |
4. | strict : It causes an error on failure, it is default, if not specified. |
5. | replace : It replaces the character with a question mark. |
6. | xmlcharrefreplace : It replaces the character with an xml character. |
1 import pandas as pd
2
3 ser = pd.Series(['Ståle', 'Straße', 'hello'])
4
5
6 s2 = ser.str.encode(encoding="utf8", errors="backslashreplace")
7 s3 = ser.str.encode(encoding="utf8", errors="ignore")
8
9
10 print(s2)
11 print(s3)
In the above example, a string variable is define with special character. A string is encoded element-wise with different encoding and errors values. An encoded string is printed on console.
1 0 b'St\xc3\xa5le'
2 1 b'Stra\xc3\x9fe'
3 2 b'hello'
4 dtype: object
5
6 0 b'St\xc3\xa5le'
7 1 b'Stra\xc3\x9fe'
8 2 b'hello'
9 dtype: object
Example with ascii
1 import pandas as pd
2
3 ser = pd.Series(['Ståle', 'Straße', 'hello'])
4
5
6 s1 = ser.str.encode(encoding="ascii", errors="namereplace")
7 s2 = ser.str.encode(encoding="ascii", errors="replace")
8 s3 = ser.str.encode(encoding="ascii", errors="backslashreplace")
9
10
11 print(s1)
12 print(s2)
13 print(s3)
In the above example, a string variable is define with special character. A string is encoded element-wise with different encoding and errors values. An encoded string is printed on console.
1 0 b'St\\N{LATIN SMALL LETTER A WITH RING ABOVE}le'
2 1 b'Stra\\N{LATIN SMALL LETTER SHARP S}e'
3 2 b'hello'
4 dtype: object
5 0 b'St?le'
6 1 b'Stra?e'
7 2 b'hello'
8 dtype: object
9 0 b'St\\xe5le'
10 1 b'Stra\\xdfe'
11 2 b'hello'
12 dtype: object
Related options for your search