python JupyterNotebook with pandas matrix() - numpy

Hi there this is my code:
When I try to run this I get an error.
df = pd.read_csv(file, sep='|', encoding='latin-1')
arreglox = df[df.columns['id':'date_in':'date_out':'objetive':'comments']].as_matrix()
arregloy = df[df.columns[1]].as_matrix()
Here is the error:
File "<ipython-input-30-6060fe26b2b1>", line 1
arreglox = df[df.columns['id':'date_in':'date_out':'objetive':'comments']].as_matrix()
^
SyntaxError: invalid syntax
please help me, thank u very much

The syntax is wrong, if you want those columns in that order try this:
arreglox = df[['id','date_in','date_out','objetive','comments']].as_matrix()

Related

tidyverse across where(!is.factor)?

I would like to create factor variables for all non-factor columns. I tried:
dat %>%
mutate(across(where(!is.factor), as.factor, .names = "{.col}_factor"))
But get error message:
Error in `mutate()`:
! Problem while computing `..1 = across(where(!is.factor), as.factor, .names = "{.col}_factor")`.
Caused by error in `across()`:
! invalid argument type
Run `rlang::last_error()` to see where the error occurred.
the where() function needs to be written as a formula, which in tidyverse shorthand is:
dat %>%
mutate(across(where(~!is.factor(.x)), as.factor, .names = "{.col}_factor"))

I get this error when i try to use Wolfram Alpha in VS code python ValueError: dictionary update sequence element #0 has length 1; 2 is required

This is my code
import wolframalpha
app_id = '876P8Q-R2PY95YEXY'
client = wolframalpha.Client(app_id)
res = client.query(input('Question: '))
print(next(res.results).text)
the question I tried was 1 + 1
and i run it and then i get this error
Traceback (most recent call last):
File "c:/Users/akshi/Desktop/Xander/Untitled.py", line 9, in <module>
print(next(res.results).text)
File "C:\Users\akshi\AppData\Local\Programs\Python\Python38\lib\site-packages\wolframalpha\__init__.py", line 166, in text
return next(iter(self.subpod)).plaintext
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Please help me
I was getting the same error when I tried to run the same code.
You can refer to "Implementing Wolfram Alpha Search" section of this website for better understanding of how the result was extracted from the dictionary returned.
https://medium.com/#salisuwy/build-an-ai-assistant-with-wolfram-alpha-and-wikipedia-in-python-d9bc8ac838fe
Also, I tried the following code by referring to the above website....hope it might help you :)
import wolframalpha
client = wolframalpha.Client('<your app_id>')
query = str(input('Question: '))
res = client.query(query)
if res['#success']=='true':
pod0=res['pod'][0]['subpod']['plaintext']
print(pod0)
pod1=res['pod'][1]
if (('definition' in pod1['#title'].lower()) or ('result' in pod1['#title'].lower()) or (pod1.get('#primary','false') == 'true')):
result = pod1['subpod']['plaintext']
print(result)
else:
print("No answer returned")

ValueError: time data 'dateConstat' does not match format

my code:
annee_now = datetime.datetime.now().strftime("%Y")
dateConstat = fields.Date(default= fields.Date.today())
fiche_emi_Struc=self.env['conformite.fiche'].search_count([(datetime.datetime.strptime(("dateConstat"),"%Y-%m-%d").strftime("%Y"),'=',annee_now)])
my message error:
ValueError: time data 'dateConstat' does not match format '%Y-%m-%d'
How Resolve it?
thanks.
Change the code like this:
annee_now = datetime.datetime.now().strftime("%Y")
dateConstat = fields.Date.today()
fiche_emi_Struc = self.env['conformite.fiche'].search_count([
((dateConstat).strftime("%Y"), '=', annee_now)
])

Autocorrect a column in a pandas dataframe using pyenchant

I tried to apply the code from the accepted answer of this question to one of my dataframe columns where each row is a sentence, but it didn't work.
My code looks this:
from enchant.checker import SpellChecker
checker = SpellChecker("id_ID")
h = df['Jawaban'].astype(str).str.lower()
hayo = []
for text in h:
checker.set_text(text)
for s in checker:
sug = s.suggest()[0]
s.replace(sug)
hayo.append(checker.get_text())
I got this following error:
IndexError: list index out of range
Any help is greatly appreciated.
I don't get the error using your code. The only thing I'm doing differently is to import the spell checker.
from enchant.checker import SpellChecker
checker = SpellChecker('en_US','en_UK') # not using id_ID
# sample data
ds = pd.DataFrame({ 'text': ['here is a spllng mstke','the wrld is grwng']})
p = ds['text'].str.lower()
hayo = []
for text in p:
checker.set_text(text)
for s in checker:
sug = s.suggest()[0]
s.replace(sug)
print(checker.get_text())
hayo.append(checker.get_text())
print(hayo)
here is a spelling mistake
the world is growing

genfromtxt in Python-3.5

I am trying to fix a data set using genfromtxt in Python 3.5. But I keep getting the next error:
ndtype = np.dtype(dict(formats=ndtype, names=names))
TypeError: data type not understood
This is the code I'm using. Any help will be appreciated!
names = ["country", "year"]
names.extend(["col%i" % (idx+1) for idx in range(682)])
dtype = "S64,i4" + ",".join(["f18" for idx in range(682)])
dataset = np.genfromtxt(data_file, dtype=dtype, names=names, delimiter=",", skip_header=1, autostrip=2)
dtype = "S64,i4" + ",".join(["f18" for idx in range(682)])
is going to produce something like:
s64,i4f18,f18,f18,f18...
Note the lack of a comma after the i4.