[英]dictionary-like get() method for rows of a pandas DataFrame?
Is there a better, more idiomatic way to do this?有没有更好、更惯用的方法来做到这一点?
import pandas as pd
df : pd.DataFrame
try:
row = df.loc[key]
except KeyError:
row = None
If I wanted a column instead of a row I could just use df.get(key)
.如果我想要一列而不是一行,我可以使用
df.get(key)
。 I tried df.transpose().get(key)
, which does work, but the transpose is not just a view, it physically transposes the data so it is quite slow when used for this purpose.我尝试
df.transpose().get(key)
,它确实有效,但转置不仅仅是一个视图,它在物理上转置数据,因此在用于此目的时它非常慢。
Use reindex
, but that would return a series of NaN
:使用
reindex
,但这会返回一系列NaN
:
df.reindex([key]).loc[key]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.