如何从pandas中的列创建一个惟一ID列表,其中ID列表在Python中被称为字符串

2024-06-02 08:03:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有熊猫数据帧数据框

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'])

测向

^{pr2}$

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

我想创建一个具有唯一ID的dataframe,这样我的unique ID frame应该包含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熊猫做到这一点呢?在


Tags: columns数据字符串importiddataframepandasdf
2条回答

这些看起来像列表的字符串表示。因此您可以使用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

使用:

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. 首先用^{}过滤掉所有非0
  2. ID列按^{}创建索引
  3. ^{}删除尾随的[ ]
  4. ^{}值并按^{}调整形状

  5. 然后通过^{}获得第一级MultiIndex,并转换^{}

  6. ^{}系列s转换为integers
  7. 获取^{}值和最后调用DataFrame构造函数

相关问题 更多 >