Python 从 Pandas 数据框中获取特定行作为系列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19599578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get particular row as series from pandas dataframe
提问by Pratyush
How do we get a particular filtered row as series?
我们如何将特定的过滤行作为系列?
Example dataframe:
示例数据框:
>>> df = pd.DataFrame({'date': [20130101, 20130101, 20130102], 'location': ['a', 'a', 'c']})
>>> df
date location
0 20130101 a
1 20130101 a
2 20130102 c
I need to select the row where location
is c
as a series.
我需要选择该行,其中location
是c
一系列。
I tried:
我试过:
row = df[df["location"] == "c"].head(1) # gives a dataframe
row = df.ix[df["location"] == "c"] # also gives a dataframe with single row
In either cases I can't the row as series.
在任何一种情况下,我都不能将行作为系列。
采纳答案by Boud
Use the squeeze
function that will remove one dimension from the dataframe:
使用squeeze
将从数据框中删除一维的函数:
df[df["location"] == "c"].squeeze()
Out[5]:
date 20130102
location c
Name: 2, dtype: object
DataFrame.squeeze
method acts the same way of the squeeze
argument of the read_csv
function when set to True
: if the resulting dataframe is a 1-len dataframe, i.e. it has only one dimension (a column or a row), then the object is squeezed down to the smaller dimension object.
DataFrame.squeeze
当设置为 时,方法的作用与函数的squeeze
参数相同:如果结果数据帧是 1-len 数据帧,即它只有一个维度(一列或一行),则对象被压缩到较小的维度目的。read_csv
True
In your case, you get a Series object from the DataFrame. The same logic applies if you squeeze a Panel down to a DataFrame.
在您的情况下,您从 DataFrame 获得一个 Series 对象。如果将 Panel 压缩为 DataFrame,则适用相同的逻辑。
squeeze is explicit in your code and shows clearly your intent to "cast down" the object in hands because its dimension can be projected to a smaller one.
挤压在您的代码中是明确的,并清楚地显示了您“放下”手中物体的意图,因为它的尺寸可以投影到更小的尺寸。
If the dataframe has more than one column or row, squeeze has no effect.
如果数据框有多于一列或多行,挤压无效。