np.r_u不适用于2个范围或多个切片

2024-09-30 20:23:13 发布

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

我的数据框形状(199,7)。我想选择列0:4和-2:(最后两列)。我想得到[final_data['unemployed']=='yes']所选列的行。我的专栏是

['panicattacks', 'compulsivebehavior', 'depression', 'anxiety','tiredness', 'unemployed', 'cluster']

  1. 我的第一次尝试返回错误ValueError: special directives must be the first entry
final_data[np.r_[final_data.columns[0:4],final_data.columns[2]]][final_data['unemployed']=='yes']
  1. 我的第二次尝试不知何故它无法工作(可能是因为.iloc,如果我错了,请纠正我)
final_data.iloc[:,np.r_[0:4,-2:]][final_data['unemployed']=='yes'] 

他们为什么不工作?我该怎么做


Tags: columns数据datanpyesfinal形状专栏
1条回答
网友
1楼 · 发布于 2024-09-30 20:23:13

这是一种生成错误消息的表达式。我在你的样品中没有看到:

In [158]: np.r_[1:3, '-1']                                                                             
                                     -
ValueError                                Traceback (most recent call last)
<ipython-input-158-0b702ddf8054> in <module>
  > 1 np.r_[1:3, '-1']

/usr/local/lib/python3.6/dist-packages/numpy/lib/index_tricks.py in __getitem__(self, key)
    358             elif isinstance(item, str):
    359                 if k != 0:
 > 360                     raise ValueError("special directives must be the "
    361                             "first entry.")
    362                 if item in ('r', 'c'):

ValueError: special directives must be the first entry.

在更简单的上下文中测试r_

In [151]: import pandas as pd                                                                          
In [152]: df = pd.DataFrame(np.arange(21).reshape(3,7))                                                
In [153]: df                                                                                           
Out[153]: 
    0   1   2   3   4   5   6
0   0   1   2   3   4   5   6
1   7   8   9  10  11  12  13
2  14  15  16  17  18  19  20

In [154]: np.r_[df.columns[0:4],df.columns[2]]                                                         
Out[154]: array([0, 1, 2, 3, 2])
In [155]: df[np.r_[df.columns[0:4],df.columns[2]]]                                                     
Out[155]: 
    0   1   2   3   2
0   0   1   2   3   2
1   7   8   9  10   9
2  14  15  16  17  16

In [150]: np.r_[0:4,-2:-1]                                                                                               
Out[150]: array([ 0,  1,  2,  3, -2])
In [156]: df.iloc[:,np.r_[0:4,-2:-1]] 
     ...:  
     ...:                                                                                              
Out[156]: 
    0   1   2   3   5
0   0   1   2   3   5
1   7   8   9  10  12
2  14  15  16  17  19

我不太确定你想要什么第二档。请记住,使用r_时,负值范围很棘手,r_不知道df.columns的大小

编辑

[154]之所以有效,是因为我的示例数据帧具有数字列标题。将其更改为字符串:

In [173]: df = pd.DataFrame(np.arange(21).reshape(3,7),columns=list('abcdefg'))                        
In [174]: df                                                                                           
Out[174]: 
    a   b   c   d   e   f   g
0   0   1   2   3   4   5   6
1   7   8   9  10  11  12  13
2  14  15  16  17  18  19  20

In [176]: df[np.r_[df.columns[0:4],df.columns[2]]]                                                     
....
ValueError: special directives must be the first entry.

引起错误的是r_

In [177]: np.r_[df.columns[0:4],df.columns[2]]                                                         
                                     -
ValueError                                Traceback (most recent call last)
<ipython-input-177-c0b1d20ac1a7> in <module>
  > 1 np.r_[df.columns[0:4],df.columns[2]]

/usr/local/lib/python3.6/dist-packages/numpy/lib/index_tricks.py in __getitem__(self, key)
    358             elif isinstance(item, str):
    359                 if k != 0:
 > 360                     raise ValueError("special directives must be the "
    361                             "first entry.")
    362                 if item in ('r', 'c'):

ValueError: special directives must be the first entry.

问题是第一个参数,一个字符串数组:

In [178]: df.columns[0:4]                                                                              
Out[178]: Index(['a', 'b', 'c', 'd'], dtype='object')

看起来最简单的解决方法是使用hstack(或者只是“连接) instead ofr{}r}r}的`切片特殊处理:

In [182]: np.hstack((df.columns[0:4],df.columns[2]))                                                   
Out[182]: array(['a', 'b', 'c', 'd', 'c'], dtype=object)

In [183]: df[np.hstack((df.columns[0:4],df.columns[2]))]                                               
Out[183]: 
    a   b   c   d   c
0   0   1   2   3   2
1   7   8   9  10   9
2  14  15  16  17  16

相关问题 更多 >