将dataframe中字符串列的唯一值转换为值为0或1的新多标头

2024-09-30 18:18:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dataframe,其列标题名为Transportation,其中一些值为Car、Bus、Ship或Nan(表示缺失值)。我要做的是提取运输中的所有唯一值(例如,id为3的人和id为6的人可能有汽车运输),然后将它们放入新的列标题中。在

然后,如果id 3的transportation是Car,那么Car头下的行值是1,其他头下的行值是0。对于Nan,所有新生成的头下的值为0。在


Tags: id标题dataframenancar汽车busship
3条回答

最简单、最快的方法是使用pandas get_dummies

示例:

考虑这个数据框df

  Transportation
0            car
1            bus
2          plane
3            NaN

如果执行此操作:

^{pr2}$

作为输出:

   bus  car  plane
0    0    1      0
1    1    0      0
2    0    0      1
3    0    0      0

我相信这就是你要找的。在

我认为这就是分类变量的二进制编码:

def binary_encode(df, field) 
    df[df['Transportation'] == field][field] = 1
    df[df['Transportation'] != field][field] = 0

例如,如果用field='Car'调用它,它将执行以下操作:

^{pr2}$

df[df['Transportation'] == 'Car']只选择dataframe中Transportation列的值为“Car”的所有行。然后,它的其余部分将值1赋给这些行的Car列。在

此时,包含Transportation列的其他值的行将具有nan,我们不希望这样。因此,我们使用类似的技术将值0赋给其余的值。在

使用内置的熊猫。应用功能。在

本例中的apply函数将接受一个函数作为输入。此函数将在列系列的每个成员上运行,并生成一个新列。下面是一个使用lambda函数和内联if else语句简洁地完成此操作的示例:

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)

得出以下结果:

Result of code

相关问题 更多 >