所以我的fd.shape (105,4)
fd.head()
Ccom Wcom Lcom Dcom
(A1, A2) (82.0, 19.0) (78.0, 99.0) (1100.0, 9520.0) (3.0, 3.0)
(A1, A3) (82.0, 25.0) (78.0, 42.0) (1100.0, 1700.0) (3.0, 7.0)
(A1, A4) (82.0, 93.0) (78.0, 37.0) (1100.0, 1700.0) (3.0, 7.0)
(A1, A5) (82.0, 9.2) (78.0, 0.44) (1100.0, 510.0) (3.0, 7.0)
(A1, A6) (82.0, 52.0) (78.0, 0.042) (1100.0, 1100.0) (3.0, 17.2)
具有来自df的所有可能组合。现在我想从每个单元格/组合中找到赢家(更大的数字(,并记下该A数字的获胜次数。输出应该是这样的:
Wins
A1 34
A2 44
A3 53
A4 76 .... and so on till last row
A15 43
这个新的数据帧基本上记录了A大于其组合的次数。
如果值是元组,则跳过此步骤。如果值是字符串,则将它们转换为元组
import ast
df = df.reset_index().applymap(ast.literal_eval).set_index('index')
现在比较这些值并从索引中的元组中提取列。输出不是预期的输出,因为示例输入数据不是整个数据帧。
import numpy as np
(df.applymap(lambda x: np.sign(x[1] - x[0]))
.apply(pd.Series.value_counts, axis=1).drop(0.0, 1)
.apply(lambda x: pd.Series(x.values, index=x.name), axis=1)
.reset_index(drop=True).T.sum(1).astype('int')
)
输出:
A1 9
A2 2
A3 2
A4 3
A5 1
A6 1
dtype: int64
复制此解决方案
将值设置为元组的数据帧
import pandas as pd
import io
import ast
a = """
Ccom Wcom Lcom Dcom
('A1', 'A2') (82.0, 19.0) (78.0, 99.0) (1100.0, 9520.0) (3.0, 3.0)
('A1', 'A3') (82.0, 25.0) (78.0, 42.0) (1100.0, 1700.0) (3.0, 7.0)
('A1', 'A4') (82.0, 93.0) (78.0, 37.0) (1100.0, 1700.0) (3.0, 7.0)
('A1', 'A5') (82.0, 9.2) (78.0, 0.44) (1100.0, 510.0) (3.0, 7.0)
('A1', 'A6') (82.0, 52.0) (78.0, 0.042) (1100.0, 1100.0) (3.0, 17.2)"""
df = pd.read_csv(io.StringIO(a), sep='ss+', engine='python')
df = df.reset_index().applymap(ast.literal_eval).set_index('index')
输出:
Ccom Wcom Lcom Dcom
index
(A1, A2) (82.0, 19.0) (78.0, 99.0) (1100.0, 9520.0) (3.0, 3.0)
(A1, A3) (82.0, 25.0) (78.0, 42.0) (1100.0, 1700.0) (3.0, 7.0)
(A1, A4) (82.0, 93.0) (78.0, 37.0) (1100.0, 1700.0) (3.0, 7.0)
(A1, A5) (82.0, 9.2) (78.0, 0.44) (1100.0, 510.0) (3.0, 7.0)
(A1, A6) (82.0, 52.0) (78.0, 0.042) (1100.0, 1100.0) (3.0, 17.2)
计算胜和平
为了避免两次计算,解决方案略有不同。要计算两名玩家的平局,需要两个值。这就是为什么用df_counts[[0,0]]
两次选择列0.0
的原因。
df_counts = (df.applymap(lambda x: np.sign(x[1] - x[0]))
.apply(pd.Series.value_counts, axis=1))
# column 'wins'
df_result = (df_counts[[-1,1]].apply(lambda x: pd.Series(x.values, index=x.name), axis=1)
.reset_index(drop=True).T.sum(1).astype('int').to_frame('wins'))
# column 'draws'
df_result['draws'] = (df_counts[[0,0]].apply(lambda x: pd.Series(x.values, index=x.name), axis=1)
.reset_index(drop=True).T.sum(1).astype('int'))
df_result
输出:
wins draws
A1 9 2
A2 2 1
A3 2 0
A4 3 0
A5 1 0
A6 1 1