Python 如何创建包含一个索引键列和多个值列的字典

Python 如何创建包含一个索引键列和多个值列的字典,python,pandas,python-2.7,dataframe,dictionary,Python,Pandas,Python 2.7,Dataframe,Dictionary,我有一个带有3列a、B、C的数据帧df。我希望a列是索引和键,B列和C列是a的值 我尝试了以下方法: def cellDict(): df_set_index('A')['B','C'] x= df.set_index('A')['B'] y= df.set_index('A')['C'] z= zip(x,y) def getCellDetails(): try: cellDB_DF= pd.read_excel('cell_DB.

我有一个带有3列a、B、C的数据帧df。我希望a列是索引和键,B列和C列是a的值

我尝试了以下方法:

def cellDict():

    df_set_index('A')['B','C']
    x= df.set_index('A')['B']
    y= df.set_index('A')['C']
    z= zip(x,y)


def getCellDetails():
    try:
        cellDB_DF= pd.read_excel('cell_DB.xlsx')
        cellLatDB= cellDB_DF['Latitude'].to_dict()
        cellLongDB= cellDB_DF['Longitude'].to_dict()
        cellDict= cellDF.set_index('Cell_ID')['Latitude']['Longitude'].to_dict()
        print cellDict

    except Exception as e:
        print e.message
预期的结果是

df{cellID}=('latitude','longitude')
然后使用字典理解:

>>> {key: (a, b) for key, a, b in df.values}
{1: (100, 400), 2: (200, 500), 3: (300, 600)}
根据@piRSquared的建议,您还可以转置数据帧,然后使用
to_dict
函数指定
list
作为方向变量

df.set_index('A').T.to_dict('list')
他的另一项建议提供了一个非常有效的解决方案:

dict(zip(df.A, zip(df.B, df.C)))
计时(Python 3.7和pandas 0.24.2)


首先初始化mydict=dict(),然后在我的手机上构建一个循环逻辑:for:mydict[cellID]=(x,y),这样我就无法验证我的答案@piRSquared,因为您的两个解决方案都有效。第一种方法非常有效(方法3),第二种方法似乎相当缓慢(方法2)。我正在使用Python3.7.3和pandas 0.24.2进行测试。我怀疑这会加快您的测试速度:“{k:(a,b)对于zip中的k,a,b(*map(df.get,df))}”
dict(zip(df.A, zip(df.B, df.C)))
# Set-up 10k row dataframe.
df = pd.DataFrame({'A': range(10000), 'B': range(10000), 'C': range(10000)})

# Method 1
%timeit -n 10 {key: (a, b) for key, a, b in df.values}
# 14.8 ms ± 3.62 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

# Method 2
%timeit -n 10 df.set_index('A').T.to_dict('list')
# 520 ms ± 41.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

# Method 3
%timeit -n 10 dict(zip(df.A, zip(df.B, df.C)))
# 7.7 ms ± 3.32 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

# Method 4
%timeit -n 10 {k: (a, b) for k, a, b in zip(*map(df.get, df))}
# 9.61 ms ± 3.81 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)