python - 如何比较两个str值数据框python pandas
问题描述
我正在尝试比较数据框中的两个不同值。我发现我无法利用的问题/答案。
import pandas as pd
# from datetime import timedelta
"""
read csv file
clean date column
convert date str to datetime
sort for equity options
replace date str column with datetime column
"""
trade_reader = pd.read_csv('TastyTrades.csv')
trade_reader['Date'] = trade_reader['Date'].replace({'T': ' ', '-0500': ''}, regex=True)
date_converter = pd.to_datetime(trade_reader['Date'], format="%Y-%m-%d %H:%M:%S")
options_frame = trade_reader.loc[(trade_reader['Instrument Type'] == 'Equity Option')]
clean_frame = options_frame.replace(to_replace=['Date'], value='date_converter')
# Separate opening transaction from closing transactions, combine frames
opens = clean_frame[clean_frame['Action'].isin(['BUY_TO_OPEN', 'SELL_TO_OPEN'])]
closes = clean_frame[clean_frame['Action'].isin(['BUY_TO_CLOSE', 'SELL_TO_CLOSE'])]
open_close_set = set(opens['Symbol']) & set(closes['Symbol'])
open_close_frame = clean_frame[clean_frame['Symbol'].isin(open_close_set)]
'''
convert Value to float
sort for trade readability
write
'''
ocf_float = open_close_frame['Value'].astype(float)
ocf_sorted = open_close_frame.sort_values(by=['Date', 'Call or Put'], ascending=True)
# for readability, revert back to ocf_sorted below
ocf_list = ocf_sorted.drop(
['Type', 'Instrument Type', 'Description', 'Quantity', 'Average Price', 'Commissions', 'Fees', 'Multiplier'], axis=1
)
ocf_list.reset_index(drop=True, inplace=True)
ocf_list['Strategy'] = ''
# ocf_list.to_csv('Sorted.csv')
# create strategy list
debit_single = []
debit_vertical = []
debit_calendar = []
credit_vertical = []
iron_condor = []
# shift columns
ocf_list['Symbol Shift'] = ocf_list['Underlying Symbol'].shift(1)
ocf_list['Symbol Check'] = ocf_list['Underlying Symbol'] == ocf_list['Symbol Shift']
# compare symbols, append depending on criteria met
for row in ocf_list:
if row['Symbol Shift'] is row['Underlying Symbol']:
debit_vertical.append(row)
print(type(ocf_list['Underlying Symbol']))
ocf_list.to_csv('Sorted.csv')
print(debit_vertical)
# delta = timedelta(seconds=10)
我得到的错误是:
line 51, in <module>
if row['Symbol Check'][-1] is row['Underlying Symbol'][-1]:
TypeError: string indices must be integers
我正在尝试将新创建的移位列与原始列进行比较,如果它们相同,则附加到列表中。有没有办法在python中比较两个字符串值?我试过检查 Symbol Check 是否为真,但它仍然返回有关str
indices must be的错误int
。.iterrows()
没用
解决方案
在这里,您实际上将遍历 DataFrame 的列,而不是行:
for row in ocf_list:
if row['Symbol Shift'] is row['Underlying Symbol']:
debit_vertical.append(row)
您可以使用其中一种方法iterrows
或itertuples
遍历行,但它们分别以列表和元组的形式返回行,这意味着您不能像在此处那样使用列名对它们进行索引。
其次,您应该使用==
而不是,is
因为您可能正在比较值,而不是身份。
最后,我将完全跳过对行的迭代,因为 pandas 是用于根据条件选择行的。您应该能够用以下代码替换上述代码:
debit_vertical = ocf_list[ocf_list['Symbol Shift'] == ocf_list['Underlying Symbol']].values.tolist()
推荐阅读
- react-native - 如何在具有本机反应的 ScrollView 中自动滚动?
- amazon-web-services - 如何更新/重命名 SQS 队列名称
- angular - HttpClient 中的 jsonp 方法没有返回错误状态 0 而不是正确的状态
- matlab - 如何在Matlab中查找句柄图形对象的所有属性、方法、事件?
- jquery - Django:尝试实现文件上传进度条
- macos - Adobe Fonts(又名 Typkekit 又名 Creative Cloud Fonts)是否在我的 Mac 上存储字体?
- r - 在R中按字母顺序对每行字符串进行排序
- javascript - 引导切换开关在页面加载时显示错误的内容
- html - 调整屏幕大小时不显示导航栏链接
- javascript - 图像在 iframe 上加载时不会全屏显示