mdicrist
mdicrist

Reputation: 175

Moving columns based on a row value from one data frame into an empty data frame in Python

I have made a 2 by n dataframe from a text file using

with open('test.txt') as a: Thresholds = pd.read_table(a, sep=',')

where the first row is a row of headers that could be different every time a new file is to be brought in, and the data consists of a row of 1s and 0s.

  A B C D E F G
  1 0 0 1 1 0 1

I am trying to then either delete all the columns with 0s or move all of the columns with 1s into an empty dataframe. I am used to writing in R or matlab and have done this in both of these languages, however I'm not too sure how to go about writing this in Python.

Any help would greatly be appreciated!

Upvotes: 1

Views: 94

Answers (2)

Scott Boston
Scott Boston

Reputation: 153470

Let's use boolean indexing on then df.columns the drop those columns from the dataframe:

df.drop(df.columns[~df.iloc[0].astype(bool)],axis=1)

Output:

   A  D  E  G
0  1  1  1  1

Upvotes: 1

Riley Hun
Riley Hun

Reputation: 2785

df = pd.DataFrame({'A': np.random.randint(0,2,1),
         'B': np.random.randint(0,2,1),
         'C': np.random.randint(0,2,1),
         'D': np.random.randint(0,2,1),
         'E': np.random.randint(0,2,1),
         'F': np.random.randint(0,2,1),
         'G': np.random.randint(0,2,1)})

mask = df.ix[0] == 1
df = df[df.columns[mask]]

This returns:

   C  D  F
0  1  1  1

Upvotes: 0

Related Questions