gpt4 book ai didi

python - 如何在 Pandas 中获得同一条船连续安装的最旧部分安装?

转载 作者:行者123 更新时间:2023-12-01 07:20:27 25 4
gpt4 key购买 nike

我有一个 pandas DataFrame,其部分安装在船上。我想保留每艘/部件的连续安装中最早的安装(参见日期)。我怎样才能做到这一点?

输入:

| date  | boat | part
|-------|------|-----
| 01/01 | A | C <-- Keep this row because this is first install of C in A
| 01/02 | A | C
| 01/03 | A | C
| 01/04 | A | D <-- Keep this row because this is first install of D in A
| 01/05 | A | D
| 01/06 | A | C <-- Keep this row because this is first install of C in A after D
| 01/07 | A | C
| 01/08 | A | C
| 01/09 | B | C <-- Keep this row because this is first install of C in B
| 01/10 | B | C

输出:

| date  | boat | part
|-------|------|-----
| 01/01 | A | C
| 01/04 | A | D
| 01/06 | A | C
| 01/09 | B | C

最佳答案

用途:

df = df[df[['boat','part']].ne(df[['boat','part']].shift()).any(axis=1)]
print (df)

date boat part
0 01/01 A C
3 01/04 A D
5 01/06 A C
8 01/09 B C

详细信息:

首先将连续值与 DataFrame.ne 进行比较和转移:

print (df[['boat','part']].ne(df[['boat','part']].shift()))
boat part
0 True True
1 False False
2 False False
3 False True
4 False False
5 False True
6 False False
7 False False
8 True False
9 False False

然后按 DataFrame.any 每行至少测试一个 True :

print (df[['boat','part']].ne(df[['boat','part']].shift()).any(axis=1))
0 True
1 False
2 False
3 True
4 False
5 True
6 False
7 False
8 True
9 False
dtype: bool

关于python - 如何在 Pandas 中获得同一条船连续安装的最旧部分安装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57726268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com