Al_Iskander - 3 months ago 23

Python Question

this is a basic question. I have dataframe like:

`1000 4000`

index

2000 NaN NaN

4000 NaN NaN

now I would like to apply a formula over the whole dataframe that could structurally look like this:

`cell_value = index_value + column_value`

i.e. the NaN's in the Dataframe should be replaced by the formula.

What would be the most elegant way to do this?

Answer

you could use apply

```
import pandas as pd
import numpy as np
df = pd.DataFrame(np.nan, index=[2000,4000], columns=[1000,4000])
df.apply(lambda x: x.name + x.index)
Out[15]:
1000 4000
2000 3000 6000
4000 5000 8000
```

since `apply()`

return columns as `Series`

calling `x.name`

returns the column name and `x.index`

is self-explanatory