- I need to ignore timestamps and loop through rows this way.
import pandas as pd
import numpy as np
time = ['11:50', '12:50', '13:50']
data_1 = {'time': time,
'n1': [1, 5, 8],
'n2': [2, 6 ,7],
'n3': [3, 7 ,6],
'n4': [4, 8, 5],
}
df1 = pd.DataFrame(data = data_1)
df1
I am trying to multiply:
- row 1 * (10^0)
- row 2 * (10^1)
- row 3 * (10^2)
- ...
- row n * (10^(n-1))
Before:
time | n1 | n2 | n3 | n4 | |
---|---|---|---|---|---|
0 | 11:50 | 1 | 2 | 3 | 4 |
1 | 12:50 | 5 |
6 |
7 |
8 |
2 | 13:50 | 8 | 7 | 6 | 5 |
Expected result:
time | n1 | n2 | n3 | n4 | |
---|---|---|---|---|---|
0 | 11:50 | 1 | 2 | 3 | 4 |
1 | 12:50 | 50 | 60 | 70 | 80 |
2 | 13:50 | 800 | 700 | 600 | 500 |
CodePudding user response:
You can use mul
on index axis:
df1.iloc[:, 1:] = df1.iloc[:, 1:].mul(10**df1.index, axis=0)
print(df1)
# Output
time n1 n2 n3 n4
0 11:50 1 2 3 4
1 12:50 50 60 70 80
2 13:50 800 700 600 500
You can replace df1.index
by np.arange(len(df1))
if your index is not a RangeIndex
.
CodePudding user response:
You can try using this also numpy broadcasting and get_indexer
,
df1.iloc[:, 1:] *= 10**df1.index.get_indexer(df1.index)[:, None]
df1
Output
time n1 n2 n3 n4
a 11:50 1 2 3 4
b 12:50 50 60 70 80
c 13:50 800 700 600 500
Works with none standard unique indexing:
Given df,
time = ['11:50', '12:50', '13:50']
data_1 = {'time': time,
'n1': [1, 5, 8],
'n2': [2, 6 ,7],
'n3': [3, 7 ,6],
'n4': [4, 8, 5],
}
df1 = pd.DataFrame(data = data_1, index=[*'abc'])
df1