Python - 转换 Pandas DataFrame 为二进制数据
使用 get_dummies() 方法将分类 DataFrame 转换为二进制数据。以下是我们具有 2 列的 Pandas DataFrame:
dataFrame = pd.DataFrame( { "Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'],"Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass'] } )
使用 get_dummies() 并设置要转换为二进制形式的列。这里,我们希望以“通过”和“未通过”形式显示结果。因此,我们设置“结果”列:
pd.get_dummies(dataFrame["Result"]
示例
以下是代码:
import pandas as pd # Create DataFrame dataFrame = pd.DataFrame( { "Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'],"Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass'] } ) print"DataFrame ...\n",dataFrame # converting to binary data dfBinary = pd.get_dummies(dataFrame["Result"]) print"\nDisplaying DataFrame in Binary form...\n",dfBinary
输出
它将产生以下输出:
DataFrame ... Result Student 0 Pass Jack 1 Fail Robin 2 Fail Ted 3 Pass Scarlett 4 Pass Kat Displaying DataFrame in Binary form... Fail Pass 0 0 1 1 1 0 2 1 0 3 0 1 4 0 1
广告