在(非常大的)熊猫数据框中定位值并将其存储到字典中

时间:2018-09-18 18:49:45

标签: python pandas dataframe optimization bigdata

我有一个很大的熊猫数据框。数据框如下所示:

>> df
    "a_1"   "a_2"   "b_1"  "c_2"  ...
"d_1" nan   0.2   nan  nan
"d_2" 0.1   nan   nan   1
"e_1" nan   1     nan  0.2
"e_2" nan   0.05  0.1  0.7
"f_2" 0.2   0.5   0.3  0.9
...

现在,我试图遍历一个元组列表,其中包含一些行名和列名:

t = [("d", "a"), ("d", "c") ...]  

例如,当i = ("d", "a")时,我想找出对应于a_1 and a_2d_1 and d_2的值,并使用以下代码定位这些值:

s = df.loc[["d_1", "d_2" ], ["a_1", "a_2"]]

# print(s)
#       "a_1"  "a_2"
# "d_1"  nan    0.2
# "d_2   0.1    nan

# convert to list and sort the values
s = s.unstack().reset_index()
s.columns = ["A","B", "Score"]
scores = s.sort_values(by="Score", ascending=False).reset_index(drop=True)

# pick the index(rank) I want and save the not-nan data to dictionary 
rank = 1
try:
    s = scores.loc[rank,:]
except Exception:
    continue

if str(s.Score) != "nan":
    d[(s.A, s.B)] = s.Score # output dictionary

现在,鉴于给定len(t) = 28350,以上代码可以工作,但是花费的时间太长,我需要测试150多个参数集。 一次迭代(一组参数)在集群上花费3.5分钟。

我想知道是否有更好的解决方案来解决这个问题。预先感谢!

1 个答案:

答案 0 :(得分:0)

那又怎么样呢?

d = {}
for row, col in t:
    vals = df.loc[df.index.str.startswith(row),
                  df.columns.str.startswith(col)].stack().dropna()
    if len(vals):
        d[vals.idxmax()] = vals.max()