Pandas Passing variable names to column name

I have a data frame that contains 13 different column names, I divided these headings into two lists. Now I want to perform various operations on each of these lists.

Is it possible to pass column names to pandas as a variable? My code at the moment can loop through the list, but I'm having problems trying to pass the column name to a 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('')
+4
source share
3 answers

I think you can use subsetone 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

Perhaps better than it listis dictionary, which is created to_dict:

d = df[CONT].count().to_dict()
print d
{'age': 3, 'fnlwgt': 3}
print d['age']
3
print d['fnlwgt']
3
0
source

to try:

for column_name, column in df.transpose().iterrows(): 
    if column_name in CONT:
        print(df[column_name].count()) 
    else: 
        print('')

edit:

: cols : df[list_of_columns] DataFrame cols list_of_columns. df[column_name] column_name

+2

Next, the counter of each column in the data frame will be printed if it is a subset of your CONT list.

CONT = ['age', 'fnlwgt', 'capital-gain', 'capital-loss']
df = pd.DataFrame(np.random.rand(5, 2), columns=CONT[:2])

>>> df
        age    fnlwgt
0  0.079796  0.736956
1  0.120187  0.778335
2  0.698782  0.691850
3  0.421074  0.369500
4  0.125983  0.454247

Select a subset of columns and do the conversion.

>>> df[[c for c in CONT if c in df]].count()
age       5
fnlwgt    5
dtype: int64
0
source

Source: https://habr.com/ru/post/1627856/


All Articles