Home > Mobile >  How to grab the previous data?
How to grab the previous data?

Time:07-26

I have a Dataframe and I want to get the previous data as an example, how can I do this?

If the previous row of A is B, get the value of B

Dataframe

df = pd.DataFrame({'Status':['A','A','A','A','A','B','A','A','A','A']})
print(df)

   Status  
0    A       
1    A
2    A
3    A
4    A
5    B <----- get the value
6    A
7    A
8    A
9    A

CodePudding user response:

You can use two masks and shift for boolean indexing:

df = pd.DataFrame({'Status':['A','A','A','A','A','B','A','A','A','A']})
m1 = df['Status'].shift(-1).eq('A')
m2 = df['Status'].eq('B')

df[m1&m2]

output:

  Status
5      B

*NB. your logic "If the previous row of A is B, get the value of B" can be rephrased into: "if the next value of a B is a A, then get the B".

intermediate masks:

  Status     m1     m2  m1&m2
0      A   True  False  False
1      A   True  False  False
2      A   True  False  False
3      A   True  False  False
4      A  False  False  False
5      B   True   True   True
6      A   True  False  False
7      A   True  False  False
8      A   True  False  False
9      A  False  False  False

CodePudding user response:

df = pd.DataFrame(
    {'Status': ['A','A','A','A','A','B','A','A','A','A']}
)
print(df)


df.loc[
    (df['Status'] == 'A').shift(-1) & (df['Status'] != 'A'),
    'Status'
]
5    B
Name: Status, dtype: object

Adding another example of DataFrame to show that other values are extracted as well:

df = pd.DataFrame(
    {'Status': ['A','A','C','A','A','B','A','A','A','A']}
)

df.loc[
    (df['Status'] == 'A').shift(-1) & (df['Status'] != 'A'),
    'Status'
]

2    C
5    B
Name: Status, dtype: object

CodePudding user response:

I think it is enough to directly determine the position of B.

df = pd.DataFrame({'Status':['A','A','A','A','A','B','A','A','A','A']})
B_df = df['Status'].eq('B')
  • Related