如何在 python 中使用数据框检查后附加列名
How to append the column names once checked with dataframe in python
我有一个数据框列列表。如果匹配,我需要检查这些名称与数据框列名称,然后它应该将 d 类型名称放入一个列表中,将 d 类型对象名称放入另一个列表中,我已经尝试过但无法将它们转换为列表。我该怎么做?
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']
在这里。
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']
我有一个数据框列列表。如果匹配,我需要检查这些名称与数据框列名称,然后它应该将 d 类型名称放入一个列表中,将 d 类型对象名称放入另一个列表中,我已经尝试过但无法将它们转换为列表。我该怎么做?
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']
在这里。
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']