Prasad Prasad - 2 months ago 6
Python Question

write csv in python based on sub-string condition

I have the following

result
variable in a data frame (
df
) and I am trying to output a csv file for those that starts with "test"

abandoned
static
test_a_1
test_b_2
abandoned
test_b_3


The following code is not working. Thanks in advance for your insights

substr="test"
if substr in df['result']:
df.to_csv("C:/Projects/result.csv",sep=',',index=False)

Answer

If what you mean is that you want to make a csv that only contains the rows for which result starta with 'test', use the following:

df[df.result.str.contains('^test.*')].to_csv("C:/Projects/result.csv",sep=',',index=False)