单热列到字符串列表的新列
One-hot columns to a new column of string list
假设我有这个数据框:
a b c d
i
0 1 0 0 0
2 0 0 0 0
4 0 1 1 0
我想添加一个新列'class'来总结索引中的每个项目class,作为字符串列表:
a b c d class
i
0 1 0 0 0 ['a']
2 0 0 0 0 NaN
4 0 1 1 0 ['b','c']
我怎样才能以稳健(处理 NaN 和多classes)和高效的方式做到这一点?
现在我将每个列值转换为 bool 类型并在应用函数中乘以它的列名但是:它不能很好地处理 multi-class 和 NaN,而且它显然不是最优的。
感谢您的帮助!
您可以使用 numpy.where
获取出现 1 的位置的索引。从那里开始,您的列索引代表标签,行索引用于对齐。此代码对我有用:
# Allocate our output first to fill nans into rows who have no labels
out = pd.Series(np.nan, index=df.index, dtype=object)
for i, j in zip(*np.where(df)):
i = df.index[i] # Extract dataframe index label instead of integer position
label = df.columns[j] # Extract relevant class label
if pd.isnull(out[i]): # If the current value in `out` is null, make a list with the class label
out[i] = [label]
else:
out[i].append(label) # If there is already a label in the out[i] cell, append to it
df["class"] = out
print(df)
a b c d class
i
0 1 0 0 0 [a]
2 0 0 0 0 NaN
4 0 1 1 0 [b, c]
假设我有这个数据框:
a b c d
i
0 1 0 0 0
2 0 0 0 0
4 0 1 1 0
我想添加一个新列'class'来总结索引中的每个项目class,作为字符串列表:
a b c d class
i
0 1 0 0 0 ['a']
2 0 0 0 0 NaN
4 0 1 1 0 ['b','c']
我怎样才能以稳健(处理 NaN 和多classes)和高效的方式做到这一点?
现在我将每个列值转换为 bool 类型并在应用函数中乘以它的列名但是:它不能很好地处理 multi-class 和 NaN,而且它显然不是最优的。
感谢您的帮助!
您可以使用 numpy.where
获取出现 1 的位置的索引。从那里开始,您的列索引代表标签,行索引用于对齐。此代码对我有用:
# Allocate our output first to fill nans into rows who have no labels
out = pd.Series(np.nan, index=df.index, dtype=object)
for i, j in zip(*np.where(df)):
i = df.index[i] # Extract dataframe index label instead of integer position
label = df.columns[j] # Extract relevant class label
if pd.isnull(out[i]): # If the current value in `out` is null, make a list with the class label
out[i] = [label]
else:
out[i].append(label) # If there is already a label in the out[i] cell, append to it
df["class"] = out
print(df)
a b c d class
i
0 1 0 0 0 [a]
2 0 0 0 0 NaN
4 0 1 1 0 [b, c]