For examples, I have a DataFrame like this:
Rank #1 Rank #2 Rank #3 Rank #4 status
0 A B D C in
1 B C A D out
2 A D C B in
3 A B C D out
4 D C B A out
5 D A C B out
...
How can I delete A values if status == out
and then shift the other row ranking values to the left?
My expected outcome is:
Rank #1 Rank #2 Rank #3 Rank #4 status
0 A B D C in
1 B C D out
2 A D C B in
3 B C D out
4 D C B out
5 D C B out
...
答案 0 :(得分:1)
这是一种方式。
import pandas as pd, numpy as np
df = pd.DataFrame({1: ['A', 'B', 'A','A', 'D', 'D'],
2: ['B', 'C', 'D', 'B', 'C', 'A'],
3: ['D', 'A', 'C', 'C', 'B', 'C'],
4: ['C', 'D', 'B', 'D', 'A', 'B'],
'status': ['in', 'out', 'in', 'out', 'out', 'out']})
mask = df['status'] == 'out'
df.loc[mask, :] = df.loc[mask, :].replace('A', '')
A = [list(''.join(i)) for i in df.iloc[:, :-1].values]
df_res = pd.DataFrame(A).fillna('').assign(result=df.status)
<强>结果强>
0 1 2 3 result
0 A B D C in
1 B C D out
2 A D C B in
3 B C D out
4 D C B out
5 D C B out
<强>解释强>