My DataFrame is:
import pandas as pd
df = pd.DataFrame(
{
'a': [20, 100],
'b': [2, 3],
'dir': ['long', 'short']
}
)
Expected output: Creating column x:
a b dir x
0 20 2 long [22, 24, 26]
1 100 3 short [97, 94, 91]
Steps:
x is a list with length of 3. a is starting point of x and b is step that a increases/decreases depending on dir. If df.dir == long x ascends otherwise it descends.
My Attempt based on this answer:
df['x'] = np.arange(0, 3) * df.b + df.a
Which does not produce the expected output.
>Solution :
One possible option :
N = 3
sign = {"long": +1, "short": -1}
df["x"] = [
np.arange(a+sb, a+sb*(N+1), step=sb)# .tolist() ?
for a,sb in zip(df["a"], df["b"].mul(df["dir"].map(sign)))
]
Output :
print(df)
a b dir x
0 20 2 long [22, 24, 26]
1 100 3 short [97, 94, 91]
[2 rows x 4 columns]