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)
Just because "test_a_1" is in the list does not mean that "test" is, in Python logic.
Example of how Python evaluates "if [string] in [list]" statements:
>>> test = 'test1'
>>> testlist = ['test1', 'test2']
>>> if 'test' in test:
... print('hi')
...
hi
>>> if 'test' in testlist:
... print('hi')
...
>>>
This would work:
substr="test"
for val in df['result']:
if substr in val:
# Do stuff
# And optionally (if you only need one CSV per dataframe rather than one CSV per result):
break
如果您的意思是要制作一个仅包含结果以“ test”开头的行的csv,请使用以下命令:
df[df.result.str.contains('^test.*')].to_csv("C:/Projects/result.csv",sep=',',index=False)
This would work :
df['temp'] = [1 if 'test' in df['result'][k] for k in df.index else 0]
df['result'][df['temp']==1].to_csv("/your/path", sep=',', index=False)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.