【问题标题】:Selecting rows with the highest value based on 1 column in the dataframe根据数据框中的 1 列选择具有最高值的行
【发布时间】:2019-06-01 11:47:05
【问题描述】:

我有一组大约 20k 行的数据框。带有标题 X、Y、Z、I、R、G、B。 (是的,它的点云)

我想通过在根据 X 列进行排序后将数据分组为 100 行来创建大量子数据帧。 随后,我想根据 Y 列对所有子数据帧进行排序,并将它们进一步分解为 50 行。(进一步分解每个子数据帧) 最终结果是我应该有一组 50 行的子数据帧,我想在每个子数据帧中挑选出 Z 值最高的所有行并将它们写入 CSV 文件。

我的代码已达到以下方法。但我不确定如何继续。

import pandas as pd
headings = ['x', 'y', 'z']
data = pd.read_table('file.csv', sep=',', skiprows=[0], names=headings)

points = data.sort_values(by=['x'])

【问题讨论】:

标签: python pandas csv


【解决方案1】:

考虑 1000 行的虚拟数据帧,

df.head()   # first 5 rows

    X   Y   Z   I   R   G   B
0   6   6   0   3   7   0   2
1   0   8   3   6   5   9   7
2   8   9   7   3   0   4   5
3   9   6   8   5   1   0   0
4   9   0   3   0   9   2   9

首先,从dataframe中提取Z的最大值,

z_max = df['Z'].max()
df = df.sort_values('X')

# list of dataframes
dfs_X = np.split(df, len(df)/ 100)

results = pd.DataFrame()
for idx, df_x in enumerate(dfs_X):
    dfs_X[idx] = df_x.sort_values('Y')
    dfs_Y = np.split(dfs_X[idx], len(dfs_X[idx]) / 50)
    for idy, df_y in enumerate(dfs_Y):
        rows = df_y[df_y['Z'] == z_max]
        results = results.append(rows)
results.head()

results 将包含来自所有数据帧的行,其最高值为Z

输出:前 5 行

    X   Y   Z   I   R   G   B
541 0   0   9   0   3   6   2
610 0   2   9   3   0   7   6
133 0   4   9   3   3   9   9
731 0   5   9   5   1   0   2
629 0   5   9   0   9   7   7

现在,使用df.to_csv() 将此数据帧写入csv

【讨论】:

    猜你喜欢
    • 2013-11-09
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2023-02-04
    • 2021-07-23
    • 2014-05-09
    • 1970-01-01
    • 2015-12-16
    相关资源
    最近更新 更多