Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

python - Pandas Passing Variable Names into Column Name

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...