熊猫字典到字典键/值列表

时间:2019-10-24 15:42:31

标签: python-3.x pandas dictionary-comprehension

我正在尝试使用数据帧中的字典嵌套列表执行列表理解,经过一些试用后,我得到了这一理解。除了使用for循环外,我还可能缺少熊猫功能吗?

use App\Policies\productsPolicy;
use App\products;

protected $policies = [
    products::class => productsPolicy::class,
];

尝试:

file = ['a.txt','a.txt','b.txt','c.txt']
year = ['2016','2017','2016','2018']
paper = ['Biology','Biology','Math','English']
name = ['Ann,Matt','Maya','Rob',np.nan]

df = pd.DataFrame({
                'file':file,
                'year':year,
                'paper':paper,
                'name':name
            })
df


dfd = df.to_dict('index')
dfd
>>>
{0: {'file': 'a.txt', 'year': '2016', 'paper': 'Biology', 'name': 'Ann,Matt'},
 1: {'file': 'a.txt', 'year': '2017', 'paper': 'Biology', 'name': 'Maya'},
 2: {'file': 'b.txt', 'year': '2016', 'paper': 'Math', 'name': 'Rob'},
 3: {'file': 'c.txt', 'year': '2018', 'paper': 'English', 'name': nan}}

我正在尝试这样获得它:元组格式。

d = []
for i in dfd.items():
    d.append(i)

>>>
[(0,
  {'file': 'a.txt', 'year': '2016', 'paper': 'Biology', 'name': 'Ann,Matt'}),
 (1, {'file': 'a.txt', 'year': '2017', 'paper': 'Biology', 'name': 'Maya'}),
 (2, {'file': 'b.txt', 'year': '2016', 'paper': 'Math', 'name': 'Rob'}),
 (3, {'file': 'c.txt', 'year': '2018', 'paper': 'English', 'name': nan})]

1 个答案:

答案 0 :(得分:1)

您在上面几乎正确。您可以使用dfd.items()一次遍历dfd字典中的键和值。然后,您可以忽略元组的关键部分,只需将值添加到列表理解中,如下所示:

d = [v for k,v in dfd.items()]

只需对数据进行测试,即可提供所需的输出