import pandas as pd
import numpy as np
# Creating a sample list which contains the transportation list
transportation_list = ["Car","Bus","Ship",np.nan,"Car","Bus","Ship",np.nan]
# Make a pandas Dataframe with a single column called transportation
df = pd.DataFrame({"Transportation":transportation_list})
# Create additional columns by applying the lambda function to each row in
# the transportation column and set the value equal to zero or one depending
# on equivalence to test value.
df['car'] = df["Transportation"].apply(lambda transport_type:1 if "Car" == transport_type else 0)
df['bus'] = df["Transportation"].apply(lambda transport_type:1 if "Bus" == transport_type else 0)
df['ship'] = df["Transportation"].apply(lambda transport_type:1 if "Ship" == transport_type else 0)
最简单、最快的方法是使用pandas get_dummies
示例:
考虑这个数据框
df
:如果执行此操作:
^{pr2}$作为输出:
我相信这就是你要找的。在
我认为这就是分类变量的二进制编码:
例如,如果用field='Car'调用它,它将执行以下操作:
^{pr2}$df[df['Transportation'] == 'Car']
只选择dataframe中Transportation
列的值为“Car”的所有行。然后,它的其余部分将值1赋给这些行的Car
列。在此时,包含
Transportation
列的其他值的行将具有nan,我们不希望这样。因此,我们使用类似的技术将值0赋给其余的值。在使用内置的熊猫。应用功能。在
本例中的apply函数将接受一个函数作为输入。此函数将在列系列的每个成员上运行,并生成一个新列。下面是一个使用lambda函数和内联if else语句简洁地完成此操作的示例:
得出以下结果:
相关问题 更多 >
编程相关推荐