在大 pandas DataFrame中获取非空元素 [英] Get non-null elements in a pandas DataFrame
本文介绍了在大 pandas DataFrame中获取非空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 DataFrame
,我想得到一些非空元素作为列表。
I have a DataFrame
and I want to get some non-null elements as a list.
具体给定 df
:
df = pd.DataFrame({"a":["A",None,"B"],"b":[None,"C","D"],"c":["E","F",None]})
a b c
0 A None E
1 None C F
2 B D None
和有趣的列列表 [a,c]
,我想提取非 - 无
元素指定列,即
and the interesting columns list ["a","c"]
, I want to extract the list of non-None
element of the specified columns, i.e.,
["A","B","E","F"]
我想我可以做
[value for colname in interesting_columns
for value in df.loc[df[colname].notnull(),colname]]
但我想知道是否有一些非迭代的魔术。
but I was wondering if there is some non-iterative magic trick.
推荐答案
您可以 stack
它长格式并使用 .values
访问者。默认情况下, stack()
自动丢失值:
You can stack
it to long format and retrieve the data with .values
accessor. By default, stack()
drops missing values automatically:
df[['a', 'c']].T.stack().values
# array(['A', 'B', 'E', 'F'], dtype=object)
或者如果你想要一个列表:
Or if you want a list:
df[['a', 'c']].T.stack().tolist()
# ['A', 'B', 'E', 'F']
T
需要按照您要求的顺序获取值。
T
is needed to get the values in the order you requested.
这篇关于在大 pandas DataFrame中获取非空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文