【问题标题】:Removing/Resampling pandas dataframe row based on condition根据条件删除/重采样熊猫数据框行
【发布时间】:2020-10-19 23:24:32
【问题描述】:

我有一个代表一些测量值的 pandas DataFrame 第一列表示一个增量非常小的连续变量 0.1 或 0.2 我需要将这个变量(和整个 DataFrame)重新采样为每 1 个增量

0     494.84284
1     494.86824
2     494.89364
3     494.91904
4     494.94444
5     494.96984
6     494.99524
7     495.02064
8     495.04604
9     495.07144
10    495.09684
11    495.12224
12    495.14764
13    495.17304
14    495.19844
15    495.22384
16    495.24924
17    495.27464
18    495.30004
19    495.32544
20    495.35084
21    495.37624
22    495.40164
23    495.42704
24    495.45244
25    495.47784
26    495.50324
27    495.52864
28    495.55404
29    495.57944

我尝试将此列设置为索引并运行以下代码,但没有成功

row_init = 0.0
for index, row in df.iterrows(): 
    if (index - row_init) < 1:
        #print (index)
        df.drop(index, inplace=True)
        row_init = index
        #print (row_init)

Example output:
0     494.84284
1     495.02064
2     496.47784
3     497.50324
4     498.52864
5     499.55404
6     500.57944

【问题讨论】:

  • 请发布数据本身,而不是照片,并显示一些您希望它看起来像的示例输出。

标签: python pandas


【解决方案1】:

看起来你只想要每个整数的第一个值,所以你可以按整数值分组并取第一个!

df = pd.DataFrame({'data':[494.84284,494.86824,494.89364,494.91904,494.94444,494.96984,494.99524,495.02064,495.04604,495.07144,495.66072,496.01247,497.5000,497.9777,500.01354]})

df.groupby(df['data'].astype(int)).first().reset_index(drop=True)

输出

         data
0   494.84284
1   495.02064
2   496.01247
3   497.50000
4   500.01354

【讨论】:

  • 谢谢,这很有帮助,是否也可以将增量增加到 2 或 3?
  • 这似乎回答了你原来的问题。也许将其标记为答案并发布另一个具有新要求的答案?
猜你喜欢
  • 2017-10-04
  • 2019-04-19
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 1970-01-01
  • 2022-08-02
  • 2015-10-15
相关资源
最近更新 更多