gpt4 book ai didi

python - Pandas 数据框过滤 ||只保留列的连续元素

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:59 31 4
gpt4 key购买 nike

我有以下数据框

import pandas as pd


df = pd.DataFrame({'a': [201, 201, 201, 201, 202, 202, 202, 203, 203, 203],
'b': [ 1, 2, 3, 5, 1, 2, 6, 1, 3, 4]})

df_filter = pd.DataFrame({'a': [ 201, 202, 203],
'b': [[1, 2, 3], [1, 2], [1]]}).set_index('a')

它们看起来像:

>>> df
a b
0 201 1
1 201 2
2 201 3
3 201 5
4 202 1
5 202 2
6 202 6
7 203 1
8 203 3
9 203 4
>>>
>>> df_filter
b
a
201 [1, 2, 3]
202 [1, 2]
203 [1]

我想使用 df_filter 过滤 df。也就是说,我想为“a”的每个元素保留“b”中相应列表的元素。

想要的结果:

>>> df_filtered
a b
0 201 1
1 201 2
2 201 3
4 202 1
5 202 2
7 203 1

此外,我实际上只想为“a”上的每个元素保留“b”的连续元素。我现在可以生成“df_filter”并使用它进行过滤,但我们非常欢迎任何可以更轻松地执行此操作的建议。

最佳答案

pandas 0.25+ 的解决方案 - 通过 Series.explode 将列表转换为行然后merge默认inner join(列名相同,所以省略on参数):

df = df_filter['b'].explode().reset_index().merge(df)
print (df)
a b
0 201 1
1 201 2
2 201 3
3 202 1
4 202 2
5 203 1

DataFrame.explode如果输入是 2 列 DataFrame:

df_filter = pd.DataFrame({'a': [      201,    202, 203],
'b': [[1, 2, 3], [1, 2], [1]]})

df = df_filter.explode('b').merge(df)
print (df)
a b
0 201 1
1 201 2
2 201 3
3 202 1
4 202 2
5 203 1

编辑:为避免重置为默认索引值,请使用 reset_indexset_index:

df = df_filter.explode('b').merge(df.reset_index()).set_index('index')
print (df)
a b
index
0 201 1
1 201 2
2 201 3
4 202 1
5 202 2
7 203 1

关于python - Pandas 数据框过滤 ||只保留列的连续元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59069909/

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