Python 基于整个数据帧的编码标签列
我的数据框架如下所示:Python 基于整个数据帧的编码标签列,python,pandas,Python,Pandas,我的数据框架如下所示: df = pd.DataFrame([[1,0,0,1], [0,1,0,0], [0,0,0,0], [1,0,0,0]], columns=list("ABCD")) >>> df A B C D 0 1 0 0 1 1 0 1 0 0 2 0 0 0 0 3 1 0 0 0 我想创建一个与df高度相同的单列数据框,带有标签,对于一行中的1和0的每个组合,它会分配一个不同的类(最好是数字),即此df应该
df = pd.DataFrame([[1,0,0,1], [0,1,0,0], [0,0,0,0], [1,0,0,0]], columns=list("ABCD"))
>>> df
A B C D
0 1 0 0 1
1 0 1 0 0
2 0 0 0 0
3 1 0 0 0
我想创建一个与df
高度相同的单列数据框,带有标签,对于一行中的1和0的每个组合,它会分配一个不同的类(最好是数字),即此df应该如下所示:
>>> df_labels
x
0 0
1 1
2 2
3 3
寻找基于pandas或sklearn等库中已有内置函数的解决方案,而不是从头开始编写代码,尽管我们非常感谢您的帮助
目前,我提出了这样的解决方案:
from sklearn.preprocessing import LabelEncoder
labels = []
for i in range(0, len(df)):
# create string from every row
val = "".join([str(x) for x in df.loc[i]])
labels.append(val)
# encode numeric labels for strings created
enc = LabelEncoder()
enc.fit(labels)
df_labels = pd.DataFrame(enc.transform(labels))
>>> df_labels
0
0 3
1 1
2 0
3 2
但是,有更好的方法吗?据我所知,没有内置的方法,但您可以这样做:
>>> df_labels
x
0 0
1 1
2 2
3 3
df.apply(lambda x:(''u').join(str(x.values)),axis=1.astype('category').cat.codes
据我所知,没有内置方法,但您可以这样做:
>>> df_labels
x
0 0
1 1
2 2
3 3
df.apply(lambda x:(“').join(str(x.values)),axis=1.astype('category').cat.code
您可以使用factorize
pd.factorize(df.apply(tuple,1))[0]
array([0, 1, 2, 3])
pd.Series(pd.factorize(df.apply(tuple,1))[0])
0 0
1 1
2 2
3 3
dtype: int64
您可以使用
factorize
pd.factorize(df.apply(tuple,1))[0]
array([0, 1, 2, 3])
pd.Series(pd.factorize(df.apply(tuple,1))[0])
0 0
1 1
2 2
3 3
dtype: int64
如果您只需要一个通用的标签编码(不按您所需的输出顺序)来分离列“a”、“B”、“C”、“D”的组合,使用
点
是一种简单的方法
n = np.arange(1, len(df.columns)+1)
Out[14]: array([1, 2, 3, 4])
df.dot(n)
Out[15]:
0 5
1 2
2 0
3 1
dtype: int64
因此,如果您只需要一个通用标签编码(而不是按照所需输出的顺序),则每个组合将被编码为
dot
提供的唯一值,使用dot来分离列“a”、“B”、“C”、“D”的组合是一种简单的方法
n = np.arange(1, len(df.columns)+1)
Out[14]: array([1, 2, 3, 4])
df.dot(n)
Out[15]:
0 5
1 2
2 0
3 1
dtype: int64
因此,每个组合将被编码为一个唯一值,由dot
提供。输出与op相同,未回答问题。输出与op相同,未回答问题。根据答案中给出的最快解决方案,这是一个非常好的主意。谢谢大家!@不客气。很高兴我能帮忙:)答案中给出的最快解决方案,真是个好主意。谢谢大家!@不客气。很高兴我能帮忙:)