从没有列标签的表中获取所选行

2024-04-18 05:04:36 发布

您现在位置:Python中文网/ 问答频道 /正文

df = pd.DataFrame([
    [-0.5, 'foo', 0],
    [ 1.5, 'bar', 1],
    [-1.5, 'foo', 2],
    [ 0.0, 'baz', 3],     
    [-0.6, '   ', 4],
    [-1.1, 'qux', 5],         
    ],columns='A B C'.split())
x = df[df['C'].isin([2,3])]
print x

结果看起来像

     A    B  C
2 -1.5  foo  2
3  0.0  baz  3

如果列没有标签

df = pd.DataFrame([
    [-0.5, 'foo', 0],
    [ 1.5, 'bar', 1],
    [-1.5, 'foo', 2],
    [ 0.0, 'baz', 3],     
    [-0.6, '   ', 4],
    [-1.1, 'qux', 5],         
    ])
x = df[df[[2]].isin([2,3])]
print x

结果看起来像

    0    1   2
0 NaN  NaN NaN
1 NaN  NaN NaN
2 NaN  NaN   2
3 NaN  NaN   3
4 NaN  NaN NaN
5 NaN  NaN NaN 

在pandas中是否可以进行行选择,而列没有标签?你知道吗


Tags: columnsdataframepandasdffoobar标签baz
2条回答

尝试使用以下代码-

x = df[df[2].isin([2,3])]

示例/演示-

In [40]: x = df[df[2].isin([2,3])]

In [41]: x
Out[41]:
     0    1  2
2 -1.5  foo  2
3  0.0  baz  3

我相信区别在于-

In [44]: type(df[[2]])
Out[44]: pandas.core.frame.DataFrame

In [46]: type(df[2])
Out[46]: pandas.core.series.Series

也可以通过使用ix索引器更显式:

df[ df.ix[:,2].isin([2,3]) ]
#     0    1  2
#2 -1.5  foo  2
#3  0.0  baz  3

相关问题 更多 >