簡體   English   中英

用於指示列表中元素的數據框列

[英]Data-frame columns to indicate elements in lists

原始數據如下:

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)

Output:

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

聰明的方法是什么? 謝謝你。

讓我們嘗試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

您可以使用 pandas 系列:

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

使用, 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

使用正常的 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)

Output

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM