我有一个包含13个不同列名的数据框,我已将这些标题分成两个列表.我现在想对每个列表执行不同的操作.
是否可以将列名作为变量传递给pandas?我的代码目前可以循环遍历列表,但我无法尝试将列名传递给函数
码
CONT = ['age','fnlwgt','capital-gain','capital-loss']
#loops through columns
for column_name, column in df.transpose().iterrows():
if column_name in CONT:
X = column_name
print(df.X.count())
else:
print('')
最佳答案 我想你可以使用从列表CONT创建的子集:
print df
age fnlwgt capital-gain
0 a 9th 5
1 b 9th 6
2 c 8th 3
CONT = ['age','fnlwgt']
print df[CONT]
age fnlwgt
0 a 9th
1 b 9th
2 c 8th
print df[CONT].count()
age 3
fnlwgt 3
dtype: int64
print df[['capital-gain']]
capital-gain
0 5
1 6
2 3
也许更好,因为列表是由to_dict
创建的字典:
d = df[CONT].count().to_dict()
print d
{'age': 3, 'fnlwgt': 3}
print d['age']
3
print d['fnlwgt']
3