将一个 DataFrame 行转换为平面列表 [英] Convert one DataFrame row to flat list

查看:66
本文介绍了将一个 DataFrame 行转换为平面列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,因此无法将 DataFrame 中的一行转换为平面 list.为此,我使用以下代码:

I new to Python and I'm therefore having trouble converting a row in a DataFrame into a flat list. To do this I use the following code:

玩具 DataFrame:

import pandas as pd
d = {
     "a": [1, 2, 3, 4, 5],
     "b": [9, 8, 7, 6, 5],
     "n": ["a", "b", "c", "d", "e"]
}

df = pd.DataFrame(d)

我的代码:

df_note = df.loc[df.n == "d", ["a", "b"]].values #convert to array
df_note = df_note.tolist() #convert to nested list
df_note = reduce(lambda x, y: x + y, df_note) #convert to flat list

在我看来,这段代码既粗俗又低效.我在 list 之前转换为 array 的事实是导致问题的原因,即要嵌套的 list .尽管如此,我找不到将行直接转换为列表的方法.有什么建议吗?

To me this code appears to be both gross and inefficient. The fact that I convert to an array before a list is what is causing the problem, i.e. the list to be nested. That withstanding, I can not find a means of converting the row directly to a list. Any advice?

这个问题不是对这个的重复.就我而言,我希望列表是扁平的.

This question is not a dupe of this. In my case, I want the list to be flat.

推荐答案

你快到了,实际上只需使用 flatten 而不是 reduce 来取消嵌套数组(而不是取消嵌套列表)和链式操作以获得单行:

You are almost there, actually just use flatten instead of reduce to unnest the array (instead of unnesting the list), and chain operations to have a one liner:

df.loc[df.n == "d", ['a','b']].values.flatten().tolist()
#[4, 6]

这篇关于将一个 DataFrame 行转换为平面列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆