import pandas as pd
data9 = pd.DataFrame([[1, 2, 3, 03:10:20:170, 'NEW',90.1060,'Agency'], [1, 2, 3, 03:10:20:144, 'Trade',90.1050,'Principal'], [1, 2, 3, 03:10:20:120, 'NEW',90.1022,'Agency'],[1, 2, 3, 03:10:20:100, 'NEW',90.1070,'Agency'], [1, 2, 3, 03:10:20:155, 'NEW',90.1051,'Principal']], columns=['A', 'B','C','D','E','F','G'])
我必须找到数据框中满足这些条件的行:
我想选择一个排序行,以便:OrderDirection 为“SELL”,则 OrderType 中“PRINCIPAL”元素的价格及其 OrderStatus 列中对应的“TRADE”元素应大于 OrderType 列中“AGENCY”元素的价格及其 OrderStatus 列中相应的“NEW”元素。 这样生成的表就只有下面的行。为此,它必须遍历整个数据帧并找到满足上述条件的所有行集。
[1, 2, 3, 03:10:20:120, 'NEW',90.1022,'Agency']
[1, 2, 3, 03:10:20:144, 'Trade',90.1050,'Principal']
我收到错误: KeyError:“标签 [True] 不在 [索引] 中”
如何解决?
代码下方:
def selection_sort(nums):
# This value of i corresponds to how many values were sorted
for i, row in nums.iterrows():
# We assume that the first item of the unsorted segment is the smallest
lowest_value_index = i
# This loop iterates over the unsorted items
for j in (i + 1, range(len(nums.F))):
if row.loc[row['G'] == 'Agency', 'F'].iloc[lowest_value_index] > row.loc[row['G'] == 'Principal', 'F' ].iloc[j]:
lowest_value_index = j
# Swap values of the lowest unsorted element with the first unsorted
# element
row.loc[row['G'] == 'Principal', 'F'].iloc[i], row.loc[row['G'] == 'Agency', 'F'].iloc[lowest_value_index] = row.loc[row['G'] == 'Agency' , 'F'].iloc[lowest_value_index], row.loc[row['G'] == 'Principal', 'F'].iloc[i]
selection_sort(data19)
最佳答案
您可以尝试.sort_values()
和.rank()
。这是我从您提供的 DataFrame 中得到的内容(时间字段需要引号,顺便说一句)。
data9 = pd.DataFrame([
[1, 2, 3, '03:10:20:170', 'NEW', 90.1060, 'Agency'],
[1, 2, 3, '03:10:20:144', 'Trade', 90.1050, 'Principal'],
[1, 2, 3, '03:10:20:120', 'NEW', 90.1022, 'Agency'],
[1, 2, 3, '03:10:20:100', 'NEW', 90.1070, 'Agency'],
[1, 2, 3, '03:10:20:155', 'NEW', 90.1051, 'Principal']
], columns=['A', 'B','C','D','E','F','G'])
按 F 和 G 列排序,但您可能可以为标称值添加临时枚举,以确保它们按照您的目的按照正确的方向排序。或者,添加时间列。
这个排序方案恰好在这里起作用,因为:
“代理机构”<“校长”,
90.1022 < 90.1050,
"new"<“贸易”,以及
03:10:20:120 < 03:10:20:144。
无论如何,如果您想使用.sort_values()
,也可以inplace
。
In [0]: data9 = data9.sort_values(by=["F","G"], ascending=[True, True])
调用data9检查结果:
In [1]: data9
Out[1]:
A B C D E F G
2 1 2 3 03:10:20:120 NEW 90.1022 Agency
1 1 2 3 03:10:20:144 Trade 90.1050 Principal
4 1 2 3 03:10:20:155 NEW 90.1051 Principal
0 1 2 3 03:10:20:170 NEW 90.1060 Agency
3 1 2 3 03:10:20:100 NEW 90.1070 Agency
然后我们可以对“F”列进行排名(您可以使用更多列,只需将它们包含在列表中,就像使用排序时一样)。之后,我们只需使用条件来选择前 2 个(低于 3 个的任何值)并生成与您的预期输出类似的结果。
In [1]: data9.loc[data9.loc[:, "F"].rank() < 3.0, :]
Out[1]:
A B C D E F G
2 1 2 3 03:10:20:120 NEW 90.1022 Agency
1 1 2 3 03:10:20:144 Trade 90.1050 Principal
关于Python 选择排序数据框行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60464921/