python - 根据值范围将数据帧拆分为较小的数据帧

标签 python pandas

我有以下数据框:

     x     text     
1    500   aa
2    550   bb
3    700   cc
4    750   dd 

如果 x 值相距超过 100 点,我的目标是拆分此 df。

是否有一个 Pandas 函数可以让您根据值的范围进行拆分?

这是我想要的输出:

df_1:
    x     text  
0   500   aa
1   550   bb

df_2:
    x     text  
0   700   cc
1   750   dd

最佳答案

我相信您需要通过助手将 groupby 对象转换为元组和字典 Series :

d = dict(tuple(df.groupby(df['x'].diff().gt(100).cumsum())))
print (d)
{0:      x text
1  500   aa
2  550   bb, 1:      x text
3  700   cc
4  750   dd}

详情 :

先通过 Series.diff 得到差值, 比较 Series.gt 更大并通过 Series.cumsum 创建连续组:
print (df['x'].diff().gt(100).cumsum())
1    0
2    0
3    1
4    1
Name: x, dtype: int32

关于python - 根据值范围将数据帧拆分为较小的数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55536609/

相关文章:

python - 机器学习/NLP 与关键字搜索以将非结构化数据转换为结构化数据

python - 如何以编程方式设置 ttk 日历

python - 对象 `astype(float)` 的 DataFrame 行为因列表或数组而异

python - 填写有关 pandas 中特定属性的缺失日期

python - Pandas Dataframe 用 stack 和 unstack reshape

python - 如何将列表项的值计数归因于新列 - pandas

python - Spacy NLP 库 : what is maximum reasonable document size

python - 了解 Sagemaker 对象检测预测的输出

python - pandas 数据帧中的时间戳

python - k 表示使用 numpy - 计算每次迭代的误差