2

I am looking for a solution to place a value based on matching a condition with the column names of the Dataframe.

Example:

A = (5000, 3500) # Column names where I want to place B
B = 'Insert here'  # String to place into Dataframe

Resulting in the empty Dataframe on the left turning into Dataframe: 

Index  3400  3500  4500 5000            Index  3400  3500  4500 5000
3400     x     x     x    x             3400     x     x     x    x
3500     x     x     x    x             3500     x     x     x    x
4500     x     x     x    x             4500     x     x     x    x
5000     x     x     x    x             5000     x     B     x    x

Frits
  • 101
  • 8
  • A better answer is provided in: https://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe-using-index – Frits Dec 02 '19 at 07:32

1 Answers1

1

You can use a transpose and stack() , then assign using loc[] and unstack:

A = (5000, 3500)
B='B'

m=df.T.stack()
m.loc[A]=B
final=m.unstack()

Index 3400 3500 4500 5000
3400     x    x    x    x
3500     x    x    x    x
4500     x    x    x    x
5000     x    B    x    x
anky
  • 64,269
  • 7
  • 30
  • 56
  • This returns me only the rows and columns that have a variable placed in them. In this example row "5000" and column "3500". The other rows and columns are not shown when unstacking. – Frits Nov 29 '19 at 07:38
  • @Frits try with `df=pd.DataFrame({3400: {3400: 'x', 3500: 'x', 4500: 'x', 5000: 'x'}, 3500: {3400: 'x', 3500: 'x', 4500: 'x', 5000: 'x'}, 4500: {3400: 'x', 3500: 'x', 4500: 'x', 5000: 'x'}, 5000: {3400: 'x', 3500: 'x', 4500: 'x', 5000: 'x'}})` and let me know, i tried with the same dataframe. – anky Nov 29 '19 at 08:08
  • are index and columns numbers or strings? it looks like numbers @Frits – anky Nov 29 '19 at 08:15
  • 1
    The problem occurs when I call the operation `m = df.T.stack()`. It creates an empty Dataframe instead of stacking the actual Dataframe, which is of a more complicated form than the Dataframe I used as an example. I am looking into this problem. Thanks for the help! – Frits Nov 29 '19 at 08:26