select data based on a string criteria python
<p>I have a large database in which I want to select all the columns that meet a certain criteria:</p>

<p>My data looks like the following:</p>

<pre><code>Name  a  b  c 
target-01  5196     24     24  
target-02  5950    150    150 
target-03  5598     50     50 
object-01  6558     44     -1 
object-02  6190     60     60 
</code></pre>

<p>I want to select all the data whose <code>Name</code> starts with <code>target</code>.</p>

<p>So the selected <code>df</code> would be:</p>

<pre><code>target-01  5196     24     24  
target-02  5950    150    150 
target-03  5598     50     50 
</code></pre>

<p>I am reading the data using:</p>

<pre><code>data = pd.read_csv('catalog.txt', sep = '\s+', header = None, skiprows =1 )
</code></pre>

<p>How can I select the data I want?</p>

<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.startswith.html" rel="nofollow"><code>str.startswith</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>

<pre><code>print (df[df.Name.str.startswith('target')])
        Name     a    b    c
0  target-01  5196   24   24
1  target-02  5950  150  150
2  target-03  5598   50   50
</code></pre>

<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow"><code>str.contains</code></a>:</p>

<pre><code>print (df[df.Name.str.contains(r'^target')])
        Name     a    b    c
0  target-01  5196   24   24
1  target-02  5950  150  150
2  target-03  5598   50   50
</code></pre>

<p>Last solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow"><code>filter</code></a>:</p>

<pre><code>df.set_index('Name', inplace=True)

print (df.filter(regex=r'^target', axis=0))
              a    b    c
Name                     
target-01  5196   24   24
target-02  5950  150  150
target-03  5598   50   50

print (df.filter(regex=r'^target', axis=0).reset_index())
        Name     a    b    c
0  target-01  5196   24   24
1  target-02  5950  150  150
2  target-03  5598   50   50
</code></pre>

python string pandas dataframe startswith