Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在按索引定向的嵌套字典中获取键和值的列表_Python_Excel_Pandas_Dictionary - Fatal编程技术网

Python 在按索引定向的嵌套字典中获取键和值的列表

Python 在按索引定向的嵌套字典中获取键和值的列表,python,excel,pandas,dictionary,Python,Excel,Pandas,Dictionary,我有一个Excel文件,其结构如下: name age status anna 35 single petr 27 married {'anna': {'age':35}, {'status': 'single'}}, {'petr': {'age':27}, {'status': 'married'}} 我已将此类文件转换为嵌套字典,其结构如下: name age status anna 35 single petr 27 married {'anna': {'age':35}, {'s

我有一个Excel文件,其结构如下:

name age status
anna 35 single
petr 27 married
{'anna': {'age':35}, {'status': 'single'}},
{'petr': {'age':27}, {'status': 'married'}}
我已将此类文件转换为嵌套字典,其结构如下:

name age status
anna 35 single
petr 27 married
{'anna': {'age':35}, {'status': 'single'}},
{'petr': {'age':27}, {'status': 'married'}}
使用熊猫:

import pandas as pd
df = pd.read_excel('path/to/file')
df.set_index('name',  inplace=True)
print(df.to_dict(orient='index'))
但是现在运行
list(df.keys())
时,它会返回字典中所有键的列表(“年龄”、“状态”等),但不会返回“名称”

我的最终目标是通过键入名称返回所有键和值

有可能吗?或者我应该使用其他方法导入数据以实现目标?最终我还是应该去查字典,因为我会用一个键将它与其他字典合并。

试试这个:

import pandas as pd
df = pd.read_excel('path/to/file')
df[df['name']=='anna'] #Get all details of anna
df[df['name']=='petr'] #Get all details of petr

给定excel中的数据框,您应该执行以下操作以获得所需的内容:

resulting_dict = {}

for name, info in df.groupby('name').apply(lambda x: x.to_dict()).iteritems():
    stats = {}
    for key, values in info.items():
        if key != 'name':
            value = list(values.values())[0]
            stats[key] = value
    resulting_dict[name] = stats

我想您需要参数
drop=False
来表示不删除列
Name

import pandas as pd
df = pd.read_excel('path/to/file')

df.set_index('name',  inplace=True, drop=False)
print (df)
      name  age   status
name                    
anna  anna   35   single
petr  petr   27  married

d = df.to_dict(orient='index')
print (d)
{'anna': {'age': 35, 'status': 'single', 'name': 'anna'}, 
 'petr': {'age': 27, 'status': 'married', 'name': 'petr'}}

print (list(df.keys()))
['name', 'age', 'status']

谢谢你,但我应该把它作为一本字典来保存,并以某种方式将“name”变成一个普通键:
my_dict=df.set_index('name').transpose()。to_dict(orient='list')
然后使用
my_dict['anna']
my_dict[
petr`]它返回我:
UserWarning:DataFrame列不是唯一的,有些列将被省略。“列将被忽略。”,UserWarning)
尽管列是唯一的