![](/img/trans.png)
[英]How to split dataframe or array by unique column value with multiple unique values
[英]Convert unique values of a string column in dataframe into new multiple header with value of 0 or 1
我有一个数据框,其标题为Transportation的列标题具有一些Car,Bus,Ship或Nan值(缺少值)。 我打算做的是提取“运输”中的所有唯一值(例如,id为3的人和id为6的人可能有汽车出行),然后将它们放入新的列标题中。
然后,如果id 3的运输方式为Car,则行值在Car标头下为1,在其他标头下为0。 对于Nan,在所有新生成的标头下,值为0。
最简单,最快的方法是使用pandas get_dummies
例:
考虑一下这个DataFrame df
:
Transportation
0 car
1 bus
2 plane
3 NaN
如果执行此命令:
new_df = pd.get_dummies(df,prefix='',prefix_sep='')
print(new_df)
你得到的输出:
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'进行调用,它将执行以下操作:
df[df['Transportation'] == 'Car']['Car'] = 1
df[df['Transportation'] != 'Car']['Car'] = 0
df[df['Transportation'] == 'Car']
仅选择数据框中“ Transportation
列的值为“汽车”的所有行。 然后,其余部分为这些行的Car
列分配值1。
此时,“ Transportation
列具有其他值的行将具有NaN,我们不希望如此。 因此,我们使用类似的技术为其余值分配值0。
使用内置的.apply函数的熊猫。
这种情况下的应用功能将以一个功能为输入。 该函数将在列系列的每个成员上运行并产生一个新列。 这是一个使用lambda函数和内联if语句来简洁地完成此操作的示例:
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)
给出以下结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.