How to add first rows from two different columns of a dataframe together, such that if column A's first row is NaN, replace with value from balance's first row, otherwise, add column A's first row and balance's first row. And so likewise column B. The idea is using balnce first row to transform first row of other columns' A and B.
I attempted using df.iloc[0] to get the first row but I'm unable to set the value or add it:
data = {'id': [1, 2, 3, 4, 5, 6],
'A': [None, None, 20, 10, 39, 30],
'B': [13, 98, 23, 45, 64, 10],
'balance': [23, 41, 12, 22, 32, 0]}
df = pd.DataFrame(data)
df = df.set_index('id')
print df
A B balance
id
1 NaN 13 23
2 NaN 98 41
3 20 23 12
4 10 45 22
5 39 64 32
6 30 10 0
for i in df.columns:
if i not in ['balance']:
if df[i].iloc[0] == None:
df[i].iloc[0] = df['balance'].iloc[0]
else:
df[i].iloc[0] = df[i].iloc[0] + df['balance'].iloc[0]
print df[i]
id
1 NaN
2 NaN
3 20
4 10
5 39
6 30
Name: A, dtype: float64
id
1 36
2 98
3 23
4 45
5 64
6 10
Name: B, dtype: int64
#A[0] should be 23, and B[0] should be 13 + 23 = 36
desired output:
id A B balance
1 23 36 23
2 NaN 98 41
3 20 23 12
4 10 45 22
5 39 64 32
6 30 10 0
balanceto transform the first rows of columns A and B. If the columns areNaN, replace both A and B withbalance. If otherwise: balance + A,balance + B`. This is only for the first rows.