RustyShackleford
RustyShackleford

Reputation: 3667

How to slice out column names based on column into row of new dataframe?

I have a df that looks like this

data.answers.1542213647002.subItemType   data.answers.1542213647002.value.1542213647003               
     thank you for the response                   TRUE

How do I slice out the column name only for columns that have the string .value. and the column has the value TRUE into a new df like so?:

new_df

old_column_names
data.answers.1542213647002.value.1542213647003  

I have roughly 100 more columns with .value. in it but not all of them have TRUE in them as values.

Upvotes: 0

Views: 96

Answers (1)

It_is_Chris
It_is_Chris

Reputation: 14103

assume this sample df:

df = pd.DataFrame({'col':[1,2]*5,
                   'col2.value.something':[True,False]*5,
                   'col3.value.something':[5]*10,
                   'col4':[True]*10})

then

# boolean indexing with stack
new = pd.DataFrame(list(df[((df==True) & (df.columns.str.contains('.value.')))].stack().index))

# drop duplicates
new = new.drop(columns=0).drop_duplicates()

    1
0   col2.value.something

Upvotes: 1

Related Questions