pandas 将变量名传递给列名 [英] Pandas Passing Variable Names into Column Name
本文介绍了 pandas 将变量名传递给列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含13个不同列名称的数据框,我将这些标题分为两个列表.我现在想对每个列表执行不同的操作.
I have a dataframe that contains 13 different column names, I have separated these headings into two lists. I now want to perform different operations on each of these lists.
是否可以将列名作为变量传递到pandas中?目前,我的代码可以很好地遍历列表,但是我在尝试将列名传递给函数时遇到困难
Is it possible to pass column names into pandas as a variable? My code at the moment can loop through the list fine but i am having trouble trying to pass the column name into the function
代码
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('')
推荐答案
我认为您可以使用从list
CONT
创建的subset
:
I think you can use subset
created from list
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
可能更好,因为list
是dictionary
,它是由 to_dict
:
Maybe better as list
is dictionary
, which is created by to_dict
:
d = df[CONT].count().to_dict()
print d
{'age': 3, 'fnlwgt': 3}
print d['age']
3
print d['fnlwgt']
3
这篇关于 pandas 将变量名传递给列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文