在pandas中,可以使用astype(bool)
方法将0和1转换为True
和False
。如果要避免这种转换,可以使用以下方法:
replace
方法将0和1替换为其他标识符(例如字符串或其他数字):import pandas as pd
df = pd.DataFrame({'col1': [0, 1, 0, 1]})
df['col1'] = df['col1'].replace({0: 'zero', 1: 'one'})
print(df['col1'])
输出:
0 zero
1 one
2 zero
3 one
Name: col1, dtype: object
import pandas as pd
df = pd.DataFrame({'col1': [0, 1, 0, 1]})
df['col1'] = df['col1'].astype(str)
print(df['col1'])
输出:
0 0
1 1
2 0
3 1
Name: col1, dtype: object
这两种方法都可以避免将0和1转换为True
和False
。根据具体需求选择适合的方法。