pandas 用于指示列表中的元素的数据框列

zpgglvta  于 2023-09-29  发布在  其他
关注(0)|答案(4)|浏览(116)

原始数据如下:

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

聪明的方法是什么?

wsxa1bj1

wsxa1bj11#

让我们试试str.get_dummiesreindex

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
bfrts1fy

bfrts1fy2#

您可以使用pandas系列:

x = pd.Series(all_names)
pd.concat([x.isin(list_0), x.isin(list_1)], axis=1).astype(int).T
anhgbhbe

anhgbhbe3#

使用,dict.fromkeys() + fillna

import pandas as pd

all_names = ['Darren', 'John', 'Kate', 'Mike', 'Nancy']

list_0 = ['John', 'Mike']
list_1 = ['Kate', 'Nancy']

df = (
    pd.DataFrame([dict.fromkeys(x, 1) for x in [list_0, list_1]],
                 columns=all_names)
).fillna(0)
Darren  John  Kate  Mike  Nancy
0     0.0   1.0   0.0   1.0    0.0
1     0.0   0.0   1.0   0.0    1.0
monwx1rj

monwx1rj4#

使用普通的pandas操作和列表解析。

import pandas as pd

all_names = ['Darren','John','Kate','Mike','Nancy']
list_0 = ['John', 'Mike']
list_1 = ['Kate', 'Nancy']

lists = [list_0, list_1]
df = pd.DataFrame(columns=all_names)

for item in lists:
    df = df.append(pd.Series([int(name in item) for name in all_names], index=df.columns), ignore_index=True)

print(df)

输出

Darren John Kate Mike Nancy
0      0    1    0    1     0
1      0    0    1    0     1

相关问题