簡體   English   中英

如何從pandas中的列創建唯一ID列表,其中ID列表在Python中被提及為字符串

[英]How to create a list of unique ID from a column in pandas where lists of ID are mentioned as strings in Python

我有一個pandas數據幀df

import pandas as pd

lst = [23682, 21963, 9711, 21175, 13022,1662,7399, 13679, 17654,4567,23608,2828, 1234]

lst_match = ['[21963]','[21175]', '[1662 7399 13679 ]','[17654 23608]','[2828]','0','0','0','0','0','0', '0','0' ]

df = pd.DataFrame(list(zip(lst, lst_match)),columns=['ID','ID_match'])

DF

       ID            ID_match
0   23682             [21963]
1   21963             [21175]
2    9711   [1662 7399 13679]
3   21175       [17654 23608]
4   13022              [2828]
5    1662                   0
6    7399                   0
7   13679                   0
8   17654                   0
9    4567                   0
10  23608                   0
11   2828                   0
12   1234                   0

ID_match列中的值也是ID,但是在字符串格式的列表中。

我想創建一個唯一ID的數據幀,使得我的唯一ID幀應該包含ID_match列中具有除0以外值的所有ID以及ID_match列中提到的那些ID。

所以我的唯一ID輸出數據框必須如下所示:

       ID           
0   23682            
1   21963             
2    9711  
3   21175       
4   13022              
5    1662                   
6    7399                  
7   13679                   
8   17654                   
9   23608                    
10   2828                  

我怎么能用python pandas做到這一點?

采用:

s = (df[df['ID_match'] != '0']
       .set_index('ID')['ID_match']
       .str.strip('[ ]')
       .str.split('\s+', expand=True)
       .stack())
print (s)
23682  0    21963
21963  0    21175
9711   0     1662
       1     7399
       2    13679
21175  0    17654
       1    23608
13022  0     2828
dtype: object


vals = s.index.get_level_values(0).to_series().append(s.astype(int)).unique()
df = pd.DataFrame({'ID':vals})
print (df)
       ID
0   23682
1   21963
2    9711
3   21175
4   13022
5    1662
6    7399
7   13679
8   17654
9   23608
10   2828

說明

  1. 首先通過boolean indexing過濾掉所有非0
  2. ID列按set_index創建索引
  3. 刪除帶strip尾隨[ ]
  4. split值並按stack重構

  5. 然后通過get_level_values獲取MultiIndex的第一級並轉換為to_series

  6. append系列s轉換為integer s
  7. 獲取unique值並最后調用DataFrame構造DataFrame

這些看起來像列表的字符串表示。 所以你可以使用ast.literal_evalitertools.chain

from ast import literal_eval
from itertools import chain

s = df['ID_match'].astype(str).str.replace(' ', ',').apply(literal_eval)
L = list(chain.from_iterable(s[s != 0]))

res = pd.DataFrame({'ID': df.loc[df['ID_match'] != 0, 'ID'].tolist() + L})\
        .drop_duplicates().reset_index(drop=True)

print(res)

       ID
0   23682
1   21963
2    9711
3   21175
4   13022
5    1662
6    7399
7   13679
8   17654
9   23608
10   2828

暫無
暫無

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

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