Copy Row(s) from One DataFrame to Another with Regex

Question:

I am trying to extract specific rows from a dataframe where values in a column contain a designated string. For example, the current dataframe looks like:

df1=

Location   Value   Name     Type
Up         10      Test A   X
Up         12      Test B   Y
Down       11      Prod 1   Y
Left       8       Test C   Y
Down       15      Prod 2   Y
Right      30      Prod 3   X

And I am trying to build a new dataframe will all rows that have "Test" in the ‘Name’ column.

df2=

Location   Value   Name     Type
Up         10      Test A   X
Up         12      Test B   Y
Left       8       Test C   Y

Is there a way to do this with regex or match?

Asked By: 2S2E

||

Answers:

How about: df2 = df1.loc[['Test' in name for name in df1.Name ]]

Answered By: dermen

Try:

df_out = df[df["Name"].str.contains("Test")]
print(df_out)

Prints:

  Location  Value    Name Type
0       Up     10  Test A    X
1       Up     12  Test B    Y
3     Left      8  Test C    Y
Answered By: Andrej Kesely
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.