Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

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

Code

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('')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
497 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...