原始数据如下:
all_names = ['Darren','John','Kate','Mike','Nancy']
list_0 = ['John', 'Mike']
list_1 = ['Kate', 'Nancy']
我要实现的是一个带有列的数据框,该列指示列表中出现了哪些名称(1表示肯定,0表示否定),例如:
我尝试了一种方法,即循环列表并通过为缺失的列表添加0来创建新列表,否则为1。
它笨拙且麻烦,特别是当列表数量增加时。
new_list_0 = []
for _ in all_names:
if _ not in list_0:
new_list_0.append(0)
else:
new_list_0.append(1)
new_list_1 = []
for _ in all_names:
if _ not in list_1:
new_list_1.append(0)
else:
new_list_1.append(1)
import pandas as pd
data = [all_names, new_list_0,new_list_1]
column_names = data.pop(0)
df = pd.DataFrame(data, columns=column_names)
输出:
Darren John Kate Mike Nancy
0 0 1 0 1 0
1 0 0 1 0 1
什么是聪明的方法?谢谢。
让我们试着str.get_dummies
和reindex
df=pd.Series([list_0,list_1]).str.join(',').str.get_dummies(',').reindex(columns=all_names,fill_value=0)
Out[160]:
Darren John Kate Mike Nancy
0 0 1 0 1 0
1 0 0 1 0 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句