在Pandas中选择行

2024-04-19 15:17:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas.DataFramedf

Property   Area   dist
A           50     2
B           100    3
C           20     10
D            1     15
E           20     16
F            3     25

我希望最终的数据帧具有以下形式:

Property   Area   dist
A           50     2
C           20     10
F            3     25

例如:我想省略每行之间的距离小于8的行。你知道吗


Tags: 数据距离dataframepandasdfdistareaproperty
1条回答
网友
1楼 · 发布于 2024-04-19 15:17:36

我相信这个代码符合你的问题陈述。基本思想是收集要保留的dist值集,然后将这些值应用于数据帧。你知道吗

代码:

# find the dist values to keep
to_keep = set()
min_value = None
min_dist = 8
for dist in sorted(df['dist']):
    if min_value <= dist - min_dist:
        min_value = dist
        to_keep.add(dist)

# build a new data frame with just the keep values
new_df = df.query('dist in @to_keep')
print(new_df)

产生:

   Area  dist
A    50     2
C    20    10
F     3    25

样本数据:

import numpy as np
import pandas as pd
props = np.array([
    ('Property', 'Area', 'dist'),
    ('A',           50,      2),
    ('B',          100,      3),
    ('C',           20,     10),
    ('D',            1,     15),
    ('E',           20,     16),
    ('F',            3,     25),
    ])

df = pd.DataFrame(data=props[1:, 1:],
                  index=props[1:, 0],
                  columns=props[0, 1:]).apply(pd.to_numeric)

相关问题 更多 >