7

I have a dataframe in a "yes/no" format like

    7   22
1   NaN t
25  t   NaN

where "t" stands for yes and I need to transform it to a X-Y table since the column name is the X coordinate and the index is the Y coordinate:

  X  Y
1 22  1
2  7 25

a pseudo-code like:

if a cell = "t":
     newdf.X = df.column(t)
     newdf.Y = df.index(t)

3 Answers 3

6

Try this:

# Use np.where to get the integer location of the 't's in the dataframe
r, c = np.where(df == 't')

# Use dataframe constructor with dataframe indexes to define X, Y
df_out = pd.DataFrame({'X':df.columns[c], 'Y':df.index[r]})
df_out

Output:

    X   Y
0  22   1
1   7  25

Update to address @RajeshC comment:

Given df,

      7   22
1   NaN    t
13  NaN  NaN
25    t  NaN

Then:

r, c = np.where(df == 't')
df_out = pd.DataFrame({'X':df.columns[c], 'Y':df.index[r]}, index=r)
df_out = df_out.reindex(range(df.shape[0]))
df_out

Output:

     X     Y
0   22   1.0
1  NaN   NaN
2    7  25.0
Sign up to request clarification or add additional context in comments.

5 Comments

In case a row doesn't contain 't', this will remove that row
@Rajesh... Yes. We need to create a more roboust example. With an expected output.
Well to the question that is asked, I think this is an excellent answer..!!
@anky Thank you for the vote of confidence.
Thank you for your support. You are a great help! also @RajeshC
5

Another option with stack:

pd.DataFrame.from_records(
    df.stack().index.swaplevel(),
    columns=['X', 'Y'])

Output:

    X   Y
0  22   1
1   7  25

Comments

0

Based on the magic of stacking, my answer is a tweak of @Perl's answer (couldn't comment because reps < 50)-

df.stack().to_frame().reset_index().drop(0,axis = 1).rename(columns = {'level_0':"Y","level_1":"X"}).reindex(columns=["X","Y"])

PS - Thanks Kristian Canler for the edit.

1 Comment

I think this might be ok as a separate answer, but please remove the images and paste in output and format it as you would format code. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.