首页 > 解决方案 > 如何在python中使用数据框检查后附加列名

问题描述

我有一个数据框列的列表。我需要检查这些名称与数据框列名称是否匹配,那么它应该将 d-type 名称放入一个列表中,并将 d-type 对象名称放入我尝试过但无法将它们转换为列表的另一个列表中。我该怎么做?

Input: 
col_lst = ['bc','fgc ','drt']
df=
   abc bc  fgc drt  
0  0   q   d  3  
1  0   g   t  1  
2  0   a   g  4 
3  0   d   c  5  
4  0   h   b  6

我的代码:

x=[]
for col in df:
    for i in col_lst:
        if i in col:
            if df[col].dtype == float or df[col].dtype == int:
                     c_int=[]
                     for i in col: c_int.append(list(i.split(","))
            elif df[col].dtype == object:
                     c_obj=[]
                     for i in col: c_obj.append(list(i.split(","))

我得到的输出:

c_int = [['d'],['r'],['t']]
c_obj=
[['b'], ['c']]
[['f'],['g'],['c']]

我需要的输出:

c_int =['drt']
c_obj =['bc','fgc']

标签: pythonlistframe

解决方案


这里是。

col_lst = ['bc','fgc','drt']                                                                                         
df = pd.DataFrame({'abc':[0,0,0,0,0], 'bc':['q','g','a','d','h'], 'fgc':['d','t','g','c','b'], 'drt':[3,1,4,5,6]})   
common = set(col_lst).intersection(set(df.columns))                                                                  
c_int=[]                                                                                                             
c_obj = []                                                                                                           
for col in common:                                                                                                   
    if df[col].dtype==float or df[col].dtype == int:                                                                 
        c_int.append(col)                                                                                            
    elif df[col].dtype == object:                                                                                    
        c_obj.append((col))                                                                                          
print(c_int)                                                                                                         
print(c_obj)

印刷:

['drt']
['fgc', 'bc']
                                                                                                  
                                                                                                                 
                                                                                                                 

推荐阅读