1

I am a Python starter using Python 3.7.0 so apologies for the blunders with my code below. I have imported an excel spreadsheet into a dataframe which shows in Jupyter as below.

    Title  Name1  Name2  Name3  Name4
0    A       P             O      P
1    B              P             O
2    C              P      P      P
3    D       P                    P

I am trying to find value 'P' for each row and print the Title label followed by all the column headers with that found value.

The desired output is better illustrated for what I am trying to achieve below:

Output:

Title A: Name1, Name4
Title B: Name2
Title C: Name2, Name3, Name4
Title D: Name1, Name4

This is my code so far:

#Sample data to recreate pd in this forum
data = {'Title':  ['A', 'B','C', 'D'],
        'Name1': ['P', '', '','P'],
        'Name2': ['', 'P','P',''],
        'Name3': ['O', '','P',''],
        'Name4': ['P', 'O','P','P'],
        }  
# Create the pandas DataFrame 
df_so = pd.DataFrame(data, columns = ['Title', 'Name1', 'Name2', 'Name3', 'Name4']) 

Neither of the codeblocks below return an output

First attempt:

for (index_label,row_series) in df_so.iterrows():
    if row_series == 'P':
        print(index_label + ':' + row_series.values)

Second attempt:

my_data = df_so.to_numpy()
for idrow, row in enumerate(my_data):
    for idcol, col in enumerate(row):
        if not pd.isnull(col):
            print("Title:" +str(idrow) + ":" + str(idcol) )

Can someone please suggest a way to achieve the desired output?

1 Answer 1

1

Convert Title to index, compare by DataFrame.eq and create new column with DataFrame.dot for matrix multiplication, last add Series.str.rstrip and convert Series to DataFrame by Series.reset_index:

df1 = df_so.set_index('Title')
df2 = df1.eq('P').dot(df1.columns + ',').str.rstrip(',').reset_index(name='new')
print (df2)
  Title                new
0     A        Name1,Name4
1     B              Name2
2     C  Name2,Name3,Name4
3     D        Name1,Name4
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Thanks a lot !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.