Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 按索引删除以字符串开头的行_Pandas - Fatal编程技术网

Pandas 按索引删除以字符串开头的行

Pandas 按索引删除以字符串开头的行,pandas,Pandas,是否可以按索引名筛选行?我需要输出索引名以“aa”和“wa”开头的行 输出: col1 col2 aaa 1 6 waa 4 2 你可以这样做 df = pd.DataFrame({'id': ['b', 'd', 'fd', 's', 'aa', 'wa', 'aaa'], 'col1': [1,2,3,4,5,6, 7]}) df.set_index('id', inplace=True) df.loc[(df.index.str.star

是否可以按索引名筛选行?我需要输出索引名以“aa”和“wa”开头的行

输出:

     col1   col2
aaa    1       6
waa    4       2

你可以这样做

df = pd.DataFrame({'id': ['b', 'd', 'fd', 's', 'aa', 'wa', 'aaa'], 'col1': [1,2,3,4,5,6, 7]})
df.set_index('id', inplace=True)
df.loc[(df.index.str.startswith('aa')) | (df.index.str.startswith('wa')), :]

这也适用于多个列

尝试使用startwith并在其中传递一个touple


import pandas as pd
df = pd.DataFrame({'col1': [3,4,5,2,1,4, 6], 'col2': [3,4,4,5,6,2, 6]}, index=['b', 'd', 'fd', 's', 'aa', 'wa', 'aaa'])

df[df.index.str.startswith(('aa', 'wa'))]
输出:

    col1  col2
aa   1       6
wa   4       2
aaa  6       6

谢谢你的回答。我也找到了解决办法

df.index.name=“type”#设置索引名称

          col1   col2
   type 
    b      3       3
    d      4       4
    fd     5       4
    s      2       5
    aaa    1       6
    waa    4       2
df.reset_index(inplace=True)#将索引类型转换为要操作的列

        type   col1   col2
    1    b      3       3
    2    d      4       4
    3    fd     5       4
    4    s      2       5
    5    aaa    1       6
    6    waa    4       2
df_aa=df[df[“type”].str.startswith('aa')]#以“aa”开头的筛选类型

df_wa=df[df[“type”].str.startswith('wa')]#以“wa”开头的筛选类型

df=pd.concat([df_aa,df_wa],axis=0)#使用轴0垂直组合数据帧

         type  col1   col2
    1    aaa    1       6
    2    waa    4       2

这里的逻辑是什么?这个解决方案还过滤索引是否包含[aaa,was],等等。就你的问题而言,答案看起来确实适合我是的,没错。所有以aa和wa开头的值。但是您的问题告诉我们不同的
输出索引名为“aa”和“wa”的行。
很抱歉,数据帧应该有额外的字母,但标题中说明了以开始。我认为就您的问题而言,现在的答案是错误的
        type   col1   col2
    1    aaa    1       6
         type  col1   col2
    1    waa    4       2
         type  col1   col2
    1    aaa    1       6
    2    waa    4       2