Выберите строки в кадре данных панд, если все столбцы содержат определенный шаблон

Вам придется играть с файловыми системами. Я добавил в закладки следующие ссылки на эту тему:

Поскольку библиотека Maciej Sobczak больше не доступна в Интернете, и, поскольку лицензия позволяет мне это сделать (исправьте меня, если я ошибаюсь), вот копия его главный файл, который мне удалось спасти от забвения:

// streamstate.h
//
// Copyright (C) Maciej Sobczak, 2002, 2003
//
// Permission to copy, use, modify, sell and distribute this software is
// granted provided this copyright notice appears in all copies.  This software
// is provided "as is" without express or implied warranty, and with no claim
// as to its suitability for any purpose.
//
// 
// 
// 

#ifndef STREAMSTATE_H_INCLUDED
#define STREAMSTATE_H_INCLUDED

#include 
#include 
#include 

// helper exception class, thrown when the source of error
// was in one of the functions managing the additional state storage
class StreamStateException : public std::ios_base::failure
{
public:
    explicit StreamStateException()
        : std::ios_base::failure(
            "Error while managing additional IOStream state.")
    {
    }
};

// State should be:
// default-constructible
// copy-constructible
// assignable

// note: the "void *" slot is used for storing the actual value
//       the "long" slot is used to propagate the error flag
template
<
    class State,
    class charT = char,
    class traits = std::char_traits
>
class streamstate
{
public:
    // construct with the default state value
    streamstate() {}

    // construct with the given stream value
    streamstate(const State &s) : state_(s) {}

    // modifies the stream
    std::basic_ios &
    modify(std::basic_ios &ios) const
    {
        long *errslot;
        void *&p = state_slot(ios, errslot);

        // propagate the error flag to the real stream state
        if (*errslot == std::ios_base::badbit)
        {
            ios.setstate(std::ios_base::badbit);
            *errslot = 0;
        }

        // here, do-nothing-in-case-of-error semantics
        if (ios.bad())
            return ios;

        if (p == NULL)
        {
            // copy existing state object if this is new slot
            p = new State(state_);
            ios.register_callback(state_callback, 0);
        }
        else
            *static_cast(p) = state_;

        return ios;
    }

    // gets the current (possibly default) state from the slot
    static State & get(std::basic_ios &ios)
    {
        long *errslot;
        void *&p = state_slot(ios, errslot);

        // propagate the error flag to the real stream state
        if (*errslot == std::ios_base::badbit)
        {
            ios.setstate(std::ios_base::badbit);
            *errslot = 0;
        }

        // this function returns a reference and therefore
        // the only sensible error reporting is via exception
        if (ios.bad())
            throw StreamStateException();

        if (p == NULL)
        {
            // create default state if this is new slot
            p = new State;
            ios.register_callback(state_callback, 0);
        }

        return *static_cast(p);
    }

private:
    // manages the destruction and format copying
    // (in the latter case performs deep copy of the state)
    static void state_callback(std::ios_base::event e,
        std::ios_base &ios, int)
    {
        long *errslot;
        if (e == std::ios_base::erase_event)
        {
            // safe delete if state_slot fails
            delete static_cast(state_slot(ios, errslot));
        }
        else if (e == std::ios_base::copyfmt_event)
        {
            void *& p = state_slot(ios, errslot);
            State *old = static_cast(p);

            // Standard forbids any exceptions from callbacks
            try
            {
                // in-place deep copy
                p = new State(*old);
    }
            catch (...)
            {
                // clean the value slot and
                // set the error flag in the error slot
                p = NULL;
                *errslot = std::ios_base::badbit;
            }
        }
    }

    // returns the references to associated slot
    static void *& state_slot(std::ios_base &ios, long *&errslot)
    {
        static int index = std::ios_base::xalloc();
        void *&p = ios.pword(index);
        errslot = &(ios.iword(index));

        // note: if pword failed,
        // then p is a valid void *& initialized to 0
        // (27.4.2.5/5)

        return p;
    }

    State state_;
};

// partial specialization for iword functionality
template
<
    class charT,
    class traits
>
class streamstate
{
public:
    // construct with the default state value
    streamstate() {}

    // construct with the given stream value
    streamstate(long s) : state_(s) {}

    // modifies the stream
    // the return value is not really useful,
    // it has to be downcasted to the expected stream type
    std::basic_ios &
    modify(std::basic_ios &ios) const
    {
        long &s = state_slot(ios);
        s = state_;

        return ios;
    }

    static long & get(std::basic_ios &ios)
    {
        return state_slot(ios);
    }

private:
    static long & state_slot(std::basic_ios &ios)
    {
        static int index = std::ios_base::xalloc();
        long &s = ios.iword(index);

        // this function returns a reference and we decide
        // to report errors via exceptions
        if (ios.bad())
            throw StreamStateException();

        return s;
    }

    long state_;
};

// convenience inserter for ostream classes
template
<
    class State,
    class charT,
    class traits
>
std::basic_ostream &
operator<<(std::basic_ostream &os,
    const streamstate &s)
{
    s.modify(os);
    return os;
}

// convenience extractor for istream classes
template
<
    class State,
    class charT,
    class traits
>
std::basic_istream &
operator>>(std::basic_istream &is,
    const streamstate &s)
{
    s.modify(is);
    return is;
}

// the alternative if there is a need to have
// many different state values of the same type
// here, the instance of streamstate_value encapsulates
// the access information (the slot index)

template
<
    class State,
    class charT = char,
    class traits = std::char_traits
>
class streamstate_value
{
public:

    streamstate_value()
        : index_(-1)
    {
    }

    // returns a reference to current (possibly default) state
    State & get(std::basic_ios &ios)
    {
        long *errslot;
        void *&p = state_slot(ios, errslot, index_);

        // propagate the error flag to the real stream state
        if (*errslot == std::ios_base::badbit)
        {
            ios.setstate(std::ios_base::badbit);
            *errslot = 0;
        }

        // this function returns a reference and the only
        // sensible way of error reporting is via exception
        if (ios.bad())
            throw StreamStateException();

        if (p == NULL)
        {
            // create default state if this is new slot
            p = new State;
            ios.register_callback(state_callback, index_);
        }

        return *static_cast(p);
    }

private:

    // manages the destruction and format copying
    // (in the latter case performs deep copy of the state)
    static void state_callback(std::ios_base::event e,
        std::ios_base &ios, int index)
    {
        long *errslot;
        if (e == std::ios_base::erase_event)
        {
            // safe delete if state_slot fails
            delete static_cast(state_slot(ios, errslot, index));
        }
        else if (e == std::ios_base::copyfmt_event)
        {
            void *& p = state_slot(ios, errslot, index);
            State *old = static_cast(p);

            // Standard forbids any exceptions from callbacks
            try
            {
                // in-place deep copy
                p = new State(*old);
    }
            catch (...)
            {
                // clean the value slot and set the error flag
                // in the error slot
                p = NULL;
                *errslot = std::ios_base::badbit;
            }
        }
    }

    // returns the references to associated slot
    static void *& state_slot(std::ios_base &ios,
        long *& errslot, int & index)
    {
        if (index < 0)
        {
            // first index usage
            index = std::ios_base::xalloc();
        }

        void *&p = ios.pword(index);
        errslot = &(ios.iword(index));

        // note: if pword failed,
        // then p is a valid void *& initialized to 0
        // (27.4.2.5/5)

        return p;
    }

    int index_;
};

// partial specialization for iword functionality
template
<
    class charT,
    class traits
>
class streamstate_value
{
public:
    // construct with the default state value
    streamstate_value()
        : index_(-1)
    {
    }

    long & get(std::basic_ios &ios)
    {
        if (index_ < 0)
        {
            // first index usage
            index_ = std::ios_base::xalloc();
        }

        long &s = ios.iword(index_);
        if (ios.bad())
            throw StreamStateException();

        return s;
    }

private:
    long index_;
};

#endif // STREAMSTATE_H_INCLUDED 

1
задан coldspeed 17 January 2019 в 05:00
поделиться

1 ответ

Начните с установки «id» в качестве индекса, если это еще не сделано.

df = df.set_index('id')

Одна опция для проверки каждой строки использует applymap, вызывая str.endswith:

df[df.applymap(lambda x: x.endswith('--')).all(1)]

   pattern1 pattern2 pattern3
id                           
2     a-a--    a-b--    a-c--
3     a-v--    a-m--    a-k--

Другая опция - apply, вызывая pd.Series.str.endswith для каждого столбца: [1115 ]

df[df.apply(lambda x: x.str.endswith('--')).all(1)]

   pattern1 pattern2 pattern3
id                           
2     a-a--    a-b--    a-c--
3     a-v--    a-m--    a-k--

И, наконец, для повышения производительности вы можете использовать маски И в пределах понимания списка, используя logical_and.reduce:

# m = np.logical_and.reduce([df[c].str.endswith('--') for c in df.columns])
m = np.logical_and.reduce([
    [x.endswith('--') for x in df[c]] for c in df.columns])
m
# array([False,  True,  True, False])

df[m]
   pattern1 pattern2 pattern3
id                           
2     a-a--    a-b--    a-c--
3     a-v--    a-m--    a-k--

Если есть другие столбцы, но вы хотите только чтобы рассмотреть те, которые названы "pattern *", вы можете использовать filter в DataFrame:

u = df.filter(like='pattern')

Теперь повторите описанные выше опции, используя u, например, первая опция будет

[ 115]

... и т. Д.

0
ответ дан coldspeed 17 January 2019 в 05:00
поделиться
Другие вопросы по тегам:

Похожие вопросы: