如何在Pandas DataFrame中插入字符串指定部分?附IB实时数据获取代码
Hey there! Let's break down your two questions and walk through solutions step by step.
If you need to insert a substring at a specific position into string values in a DataFrame column, Pandas has a handy built-in method called str.insert() that's perfect for this. Here's how it works with a quick example:
import pandas as pd # 创建示例DataFrame df = pd.DataFrame({'original_text': ['hello', 'world', 'pandas']}) # 在每个字符串的索引位置2(从0开始计数)插入下划线'_' df['modified_text'] = df['original_text'].str.insert(2, '_') print(df)
This will output:
original_text modified_text 0 hello he_llo 1 world wo_rld 2 pandas pa_ndas
For more custom logic—like inserting different substrings based on conditions—you can use apply() with a custom function:
def insert_custom_substring(text, insert_pos, substring): # 拆分字符串并插入指定内容 return text[:insert_pos] + substring + text[insert_pos:] # 在索引位置3插入'xxx'到每个字符串 df['custom_modified'] = df['original_text'].apply(insert_custom_substring, args=(3, 'xxx')) print(df)
Your existing code has a solid foundation, but the onBarUpdate callback is incomplete. Let's flesh it out to properly capture 5-second real-time bars and store them in a DataFrame. Here's the full, working version:
import pandas as pd import datetime from ib_insync import * # 初始化IB连接 ib = IB() ib.connect('127.0.0.1', 7496, clientId=1) # 创建空DataFrame存储实时Bar数据 real_time_data = pd.DataFrame(columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']) def SimpleFuture(): contract = Contract() contract.symbol = "GXBT" contract.secType = "FUT" contract.exchange = "CFECRYPTO" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "201805" return contract def onBarUpdate(bars, hasNewBar): if hasNewBar: # 获取最新的Bar数据 latest_bar = bars[-1] # 整理成DataFrame可接受的格式 new_entry = { 'timestamp': datetime.datetime.fromtimestamp(latest_bar.date), 'open': latest_bar.open, 'high': latest_bar.high, 'low': latest_bar.low, 'close': latest_bar.close, 'volume': latest_bar.volume } # 全局引用DataFrame并追加数据 global real_time_data real_time_data = pd.concat([real_time_data, pd.DataFrame([new_entry])], ignore_index=True) print(f"New 5-second bar added:\n{new_entry}\n") # 获取合约对象 crypto_future = SimpleFuture() # 请求5秒间隔的实时Bar数据(barSize=5对应5秒) ib.reqRealTimeBars( contract=crypto_future, barSize=5, whatToShow='MIDPOINT', useRTH=True, keepUpToDate=True, callback=onBarUpdate ) # 保持IB客户端运行以接收实时数据 ib.run()
Key Notes:
- We initialized
real_time_datato store each incoming 5-second bar - The
onBarUpdatecallback checks for new bars, extracts the data, and appends it to the DataFrame barSize=5inreqRealTimeBarsensures we get data every 5 secondsib.run()keeps the connection alive and processes real-time events
If you wanted tick-level data instead of bars, you'd switch to reqMktData with a tick-focused callback:
def onTickUpdate(ticker): print(f"Latest tick price: {ticker.last}") ib.reqMktData(crypto_future, '', False, False, callback=onTickUpdate) ib.run()
内容的提问来源于stack exchange,提问作者Rich

