python - 效率: Dropping rows with the same timestamp while still having the median of second column for that timestamp

标签 python pandas numpy bigdata

我想做的事: 列“角度”每秒跟踪约 20 个角度(可能会有所不同)。但我的“时间”时间戳的精度只有 1 秒(因此总是大约 20 行具有相同的时间戳)(数据帧中的总行数超过 100 万行)。 我的结果应该是一个新的数据帧,每行的时间戳都在变化。时间戳的角度应为该间隔内 ~20 个时间戳的中位数。

我的想法: 我遍历行并检查时间戳是否已更改。 如果是这样,我选择所有时间戳直到它发生变化,计算中位数,并将其附加到新的数据帧。 尽管如此,我有很多大数据文件,我想知道是否有更快的方法来实现我的目标。

现在我的代码如下(见下文)。 它并不快,我认为必须有更好的方法来使用 pandas/numpy (或其他东西?)来做到这一点。

a = 0
for i in range(1,len(df1.index)):
    if df1.iloc[[a],[1]].iloc[0][0]==df1.iloc[[i],[1]].iloc[0][0]:
        continue
    else:
        if a == 0:
            df_result = df1[a:i-1].median()
        else:
            df_result = df_result.append(df1[a:i-1].median(), ignore_index = True)
    a = i

最佳答案

您可以在此处使用groupby。下面,我制作了一个简单的虚拟数据框。

import pandas as pd
df1 = pd.DataFrame({'time': [1,1,1,1,1,1,2,2,2,2,2,2],
                   'angle' : [8,9,7,1,4,5,11,4,3,8,7,6]})

df1

  time  angle
0   1   8
1   1   9
2   1   7
3   1   1
4   1   4
5   1   5
6   2   11
7   2   4
8   2   3
9   2   8
10  2   7
11  2   6

然后,我们按时间戳进行分组,并取该组内角度列的中位数,并将结果转换为 pandas 数据帧。

df2 =  pd.DataFrame(df1.groupby('time')['angle'].median())
df2 = df2.reset_index()
df2

    time angle
0   1     6.0
1   2     6.5

关于python - 效率: Dropping rows with the same timestamp while still having the median of second column for that timestamp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58990878/

相关文章:

python - Foreach 循环使用 BeautifulSoup/Mechanize/Python 获取下一页链接

python - 在 Pandas 中连接两个 df

python - 使用附加列识别重复的行

python - 如何用另一个数组创建或填充一个 numpy 数组?

python - 在二维数组中进行所有可能的组合

python - numpy字节到纯字符串

python - 将 pandas 列中的字典转换为数据框

python - 只允许 pyqt4 应用程序的一个实例

python - 有一种快速的方法可以知道 Anaconda 中是否安装了一个包

python - 根据 ID 状态转换数据帧