I have a question regarding the Python Pandas data change

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

One column of the data frame being created has a value of one of the three types of A neutral B I want to change all of these neutral values to the most recent A or B values For example, if you get A neutral, B neutral, B neutral, B neutral, A neutral, B neutral, B neutral, I want to make it like this

python google pandas

2022-09-20 12:34

1 Answers

Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({"col"):list("A Neutral B Neutral B Neutral B Neutral A Neutral B Neutral".split())})
>>> df
   col
0    A
1 Neutral
2 Neutral
3    B
4 Neutral
5 Neutral
6    B
7    A
8 Neutral
9    A
10 Neutral
11   B
12 Neutral
>>> df["col"].replace("neutral", np.NaN)
0       A
1     NaN
2     NaN
3       B
4     NaN
5     NaN
6       B
7       A
8     NaN
9       A
10    NaN
11      B
12    NaN
Name: col, dtype: object
>>> df["col"].replace("neutral", np.NaN).fillna(method="fill")
0     A
1     A
2     A
3     B
4     B
5     B
6     B
7     A
8     A
9     A
10    A
11    B
12    B
Name: col, dtype: object
>>> df["col"] = df["col"].replace("neutral", np.NaN).fillna(method="fill")
>>> df
   col
0    A
1    A
2    A
3    B
4    B
5    B
6    B
7    A
8    A
9    A
10   A
11   B
12   B
>>> 


2022-09-20 12:34

If you have any answers or tips


© 2022 pinfo. All rights reserved.