How do I enable the REFS_OK flag in nditer in numpy in Python 3.3?
Asked Answered
F

2

11

Does anyone know how one goes about enabling the REFS_OK flag in numpy? I cannot seem to find a clear explanation online.

My code is:

import sys
import string
import numpy as np
import pandas as pd
SNP_df = pd.read_csv('SNPs.txt',sep='\t',index_col = None ,header = None,nrows = 101)
output = open('100 SNPs.fa','a')
for i in SNP_df:
    data = SNP_df[i]
    data = np.array(data)
    for j in np.nditer(data):
        if j == 0:
            output.write(("\n>%s\n")%(str(data(j))))
        else:
            output.write(data(j))

I keep getting the error message: Iterator operand or requested dtype holds references, but the REFS_OK was not enabled.

I cannot work out how to enable the REFS_OK flag so the program can continue...

Fetterlock answered 3/5, 2013 at 17:44 Comment(2)
did you check the np.nditer documentation? I admit nditer is a bit lowlevel, but the doc does say how to pass flags and mentions refs_ok, so what did you try?Locality
Thank you seberg. I found a way around using np.nditerFetterlock
F
4

I have isolated the problem. There is no need to use np.nditer. The main problem was with me misinterpreting how Python would read iterator variables in a for loop. The corrected code is below.

import sys
import string
import fileinput
import numpy as np

SNP_df = pd.read_csv('datafile.txt',sep='\t',index_col = None ,header = None,nrows = 5000)
output = open('outputFile.fa','a')

for i in range(1,51): 
    data = SNP_df[i]
    data = np.array(data)
    for j in range(0,1): 
        output.write(("\n>%s\n")%(str(data[j])))
    for k in range(1,len(data)):
        output.write(str(data[k]))
Fetterlock answered 7/5, 2013 at 18:1 Comment(0)
M
3

If you really want to enable the flag, I have an working example.

Python 2.7, numpy 1.14.2, pandas 0.22.0

import pandas as pd
import numpy as np

# get all data as panda DataFrame
data = pd.read_csv("./monthdata.csv")
print(data)

# get values as numpy array
data_ar = data.values # numpy.ndarray, every element is a row
for row in data_ar:
    print(row)
    sum = 0
    count = 0
    for month in np.nditer(row, flags=["refs_OK"], op_flags=["readwrite"]):
        print month
Molest answered 5/4, 2018 at 16:49 Comment(2)
in my case (python 3.6, numpy 1.18.1) I only had to change the flags to lower case flags=("refs_ok"])Grot
Thanks. I think the flag changed some time ago.Molest

© 2022 - 2024 — McMap. All rights reserved.