将某个大的dataframe进行groupby后,将某列中的n-1个分递增的增加0.1

使用Pythonpandas处理数据:分组、删除和调整非重要节点的坐标
文章介绍了如何使用Python中的pandas和numpy库对DataFrame进行操作,包括按geom分组、过滤非重要节点(type=0),以及在必要时调整重要节点(type!=0)的坐标。
import pandas as pd
import numpy as np

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
d = [10, 21, 10, 21, 21, 10, 23, 23, 25, 25]
f = [0, 1, 1, 2, 0, 0, 2, 2, 0, 0]
df = pd.DataFrame({'id': a, 'geom': d, 'type': f})
#
df = df[['id', 'geom', 'type']]
df_group = df.groupby('geom')
for i, j in df_group:
    print("j:", j)
    unique_values = j['type'].unique()
    # 第一种情况:都是非重要的节点
    if len(unique_values) == 1 and unique_values[0] == 0:
        print("将这个dataframe只保留一条数据")
    else:
        # 1、先将type为节点的数据删除(数据库中删除)
        df_normal = j[j['type'] == 0]
        print("df_normal:", df_normal)

        # 2、判断df_的大小,如果只有一条的不用管,大于一条的修改坐标
        df_ = j[j['type'] != 0]
        print("df_:",df_)
        if len(df_) != 1:
            number = np.concatenate(([0], np.arange(0.1, (df_.shape[0] - 1) * 0.1 + 0.1, 0.1)))
            df_['geom'] = df_['geom'] + number
            print("df_更改后:", df_)

结果

j:    id  geom  type
0   1    10     0
2   3    10     1
5   6    10     0
df_normal:    id  geom  type
0   1    10     0
5   6    10     0
df_:    id  geom  type
2   3    10     1
j:    id  geom  type
1   2    21     1
3   4    21     2
4   5    21     0
df_normal:    id  geom  type
4   5    21     0
df_:    id  geom  type
1   2    21     1
3   4    21     2
df_更改后:    id  geom  type
1   2  21.0     1
3   4  21.1     2
j:    id  geom  type
6   7    23     2
7   8    23     2
df_normal: Empty DataFrame
Columns: [id, geom, type]
Index: []
df_:    id  geom  type
6   7    23     2
7   8    23     2
df_更改后:    id  geom  type
6   7  23.0     2
7   8  23.1     2
j:    id  geom  type
8   9    25     0
9  10    25     0
将这个dataframe只保留一条数据
模块 5:工业应用场景的数据析问题 内容 5.1:数据处理实验 ETL 要求:以工业领域为背景,用 Python 生成一个模拟数据集,并用 Python 语言完成 ETL 操作,给出流程的详细解释。 在工业领域中,数据可能来自多个来源,如传感器、机器运行日志、质量检 查结果等。我们可以假设有一个示例数据集,其中包含以下信息: 机器 ID 传感器测量的温度(单位:摄氏度) 传感器测量的湿度(单位:百比) 时间戳 机器状态(正常、故障) 质量检查结果(通过/未通过) 示例数据集 (CSV 格式) csv Copy code MachineID,Temperature,Humidity,Timestamp,MachineStatus,QualityCheck M001,45.5,30.0,2024-08-01 08:00:00,Normal,Pass M002,60.0,40.5,2024-08-01 08:05:00,Fault,Fail M003,50.0,35.0,2024-08-01 08:10:00,Normal,Pass M001,48.5,33.0,2024-08-01 08:15:00,Normal,Pass M002,62.5,42.0,2024-08-01 08:20:00,Fault,Fail M003,51.0,36.0,2024-08-01 08:25:00,Normal,Pass ETL 操作流程 ETL(Extract, Transform, Load)是数据处理的核心步骤,通常包括以下三个阶段: 1. 抽取 (Extract) 抽取数据阶段可以从多个数据源中获取原始数据,如 CSV 文件、数据库或传感 器系统。这个阶段的主要目的是将数据导入系统,以便进一步处理。 2. 转换 (Transform转换阶段对原始数据进行清洗和处理,以确保其一致性和质量。典型的转换操作 包括:  处理缺失值  转换数据类型  数据标准化(例如,将温度转换为摄氏度或华氏度)  计算派生(如温度的平均值、湿度的变化率)  根据业务规则筛选和过滤数据 3. 加载 (Load) 将转换后的数据加载到目标系统,如数据仓库、数据库或析平台,以供进一步 的析和可视化使用。
03-25
# 克隆自聚宽文章:https://www.joinquant.com/post/3996 # 标题:【量化课堂】基于修正TD指标的指数择时策略 # 作者:JoinQuant量化课堂 #TD组合策略 def initialize(context): set_params() #1设置策参数 set_variables() #2设置中间变量 set_backtest() #3设置回测条件 g.stock = '000300.XSHG' #沪深300指数作为交易对象 set_benchmark('000300.XSHG') def set_params(): g.buy_init = 0 #买入启动阶段计数,直到满足g.init_len为止 g.sell_init = 0 #卖出启动阶段计数,直到满足g.init_len为止 g.buy_count_1 = 0 #买入计数1,直到达到g.count_num为止 g.buy_count_2 = 0 #买入计数2,直到达到g.count_num为止 g.sell_count_1 = 0 #卖出计数1,直到达到g.count_num为止 g.sell_count_2 = 0 #卖出计数2,直到达到g.count_num为止 g.state = 'empty' #仓位状态,是满仓还是空仓 g.save_price = 0 #记录上次保存的价格状态 g.init_lag = 4 #启动阶段和此前第四天的价格进行比较 g.init_len = 4 #启动阶段为4 g.count_lag = 2 #计数阶段和此前第二天的价格进行比较 g.count_num = 14 #计数阶段临界值为14和28,计数1达到14或者计数2达到28则达到安全买卖点 g.low=0.0 #用来保存计数阶段K线的最低值,从而判断是否达到止损条件 def set_variables(): g.t=0 #记录回测运行的天数 def set_backtest(): set_option('use_real_price', True)#用真实价格交易 log.set_level('order', 'error') ''' ================================================================================ 每天开盘前 ================================================================================ ''' #每天开盘前要做的事情 def before_trading_start(context): # 根据不同的时间段设置滑点与手续费 set_slip_fee(context) g.t+=1 # 根据不同的时间段设置滑点与手续费 def set_slip_fee(context): # 将滑点设置为0 set_slippage(FixedSlippage(0)) # 根据不同的时间段设置手续费 dt=context.current_dt log.info(type(context.current_dt)) if dt>datetime.datetime(2013,1, 1): set_commission(PerTrade(buy_cost=0.0003, sell_cost=0.0013, min_cost=5)) elif dt>datetime.datetime(2011,1, 1): set_commission(PerTrade(buy_cost=0.001, sell_cost=0.002, min_cost=5)) elif dt>datetime.datetime(2009,1, 1): set_commission(PerTrade(buy_cost=0.002, sell_cost=0.003, min_cost=5)) else: set_commission(PerTrade(buy_cost=0.003, sell_cost=0.004, min_cost=5)) ''' ================================================================================ 每天交易时 ================================================================================ ''' def handle_data(context, data): #获取交易信号 signal = get_signal(context) #根据交易信号买入卖出 rebalance(signal, context) #获取交易信号,并判断是买入还是卖出 def get_signal(context): #如果当前仓位为空,则寻找买入启动,找到后进行买入计数 if g.state == 'empty': prices = list(attribute_history(g.stock, g.init_lag+1, '1d', 'close').close) prices_low=list(attribute_history(g.stock, g.init_lag+1, '1d', 'low').low) if prices[-1]<prices[0]: g.buy_init += 1 else: g.buy_init = 0 if g.buy_init == g.init_len: g.state = 'buy_count' g.buy_init = 0 g.save_price = prices[-1] g.low=prices_low[-1] return 'poop' #如果当前仓位已满,则寻找卖出计数,找到后进行卖出计数 elif g.state == 'full': prices = list(attribute_history(g.stock, g.init_lag+1, '1d', 'close').close) prices_low=list(attribute_history(g.stock, g.init_lag+1, '1d', 'low').low) if(g.low>prices_low[-1]): return 'sell' if prices[-1]>prices[0]: g.sell_init += 1 else: g.sell_init = 0 if g.sell_init == g.init_len: g.state = 'sell_count' g.sell_init = 0 g.save_price = prices[-1] return 'poop' #如果是买入计数则判断是否到达安全买点,如到达则买入 elif g.state == 'buy_count': prices = attribute_history(g.stock, g.count_lag+1, '1d', ['close','high','low']) closes = list(prices.close) highs = list(prices.high) lows = list(prices.low) if closes[-1]<closes[0] or lows[-1]<lows[-2] or closes[-1]<g.save_price: if(g.low>lows[-1]): g.low=lows[-1] g.buy_count_1 += 1 elif closes[-1]>closes[0] or highs[-1]>highs[-2] or closes[-1]>g.save_price: if(g.low>lows[-1]): g.low=lows[-1] g.buy_count_2 += 1 if g.buy_count_1 == g.count_num*2 or g.buy_count_2 == g.count_num: g.state = 'full' g.buy_count_1 = 0 g.buy_count_2 = 0 return 'buy' #如果是卖出计数则判断是否到达安全卖点,如到达则卖出 elif g.state == 'sell_count': prices = attribute_history(g.stock, g.count_lag+1, '1d', ['close','high','low']) closes = list(prices.close) highs = list(prices.high) lows = list(prices.low) if closes[-1]<closes[0] or lows[-1]<lows[-2] or closes[-1]<g.save_price: g.sell_count_2 += 1 elif closes[-1]>closes[0] or highs[-1]>highs[-2] or closes[-1]>g.save_price: g.sell_count_1 += 1 if g.sell_count_1 == g.count_num*2 or g.sell_count_2 == g.count_num: g.state = 'empty' g.sell_count_1 = 0 g.sell_count_2 = 0 return 'sell' #根据获得的信号进行买入卖出操作,并将最低点计数归为0 def rebalance(signal, context): if signal=='buy': order_target_value(g.stock, context.portfolio.total_value) if signal=='sell': if(g.low!=0): order_target(g.stock, 0) #每次将仓位平空后,重新将计数期间K线最低点设置为0 g.low=0.0
09-25
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值