Create list of row elements – Python

Question:

I want to create a column B from Column A elements as shown below in panadas dataframe.
Center image description here

Can anyone please help?

I basically want to calculate rolling median for Column ‘A’ . Can anyone tell the alternative of column B as well to calculate the same

Asked By: Abhinav Khandelwal

||

Answers:

If need lists use Series.expanding in list comprehension:

df = pd.DataFrame({'A':range(1, 7)})

df['B'] = [x.tolist() for x in df.A.expanding()]
print (df)
   A                   B
0  1                 [1]
1  2              [1, 2]
2  3           [1, 2, 3]
3  4        [1, 2, 3, 4]
4  5     [1, 2, 3, 4, 5]
5  6  [1, 2, 3, 4, 5, 6]

Alternative:

L = df.A.tolist()
df['B'] = [L[:i] for i, x in enumerate(L,1)]

If need median use Expanding.median:

df = pd.DataFrame({'A':range(1, 7)})

df['B'] = df.A.expanding().median()
print (df)
   A    B
0  1  1.0
1  2  1.5
2  3  2.0
3  4  2.5
4  5  3.0
5  6  3.5
Answered By: jezrael

Example

df = pd.DataFrame([1, 2, 3, 4, 5, 6], columns=['A'])

df

    A
0   1
1   2
2   3
3   4
4   5
5   6

Code

out = df.assign(B=df['A'].expanding().median())

out

    A   B
0   1   1.0
1   2   1.5
2   3   2.0
3   4   2.5
4   5   3.0
5   6   3.5
Answered By: Panda Kim
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.