The return statement not working as expected - return

So I am trying to write a function which edits a dataframe in place- drops a column and adds another column to it. Within the function I am getting the expected output, but when I am trying to print the dataframe outside the function, it is still printing the original values:
import pandas as pd
import numpy as np
def login_table(id_name_verified, id_password):
"""
:param id_name_verified: (DataFrame) DataFrame with columns: Id, Login, Verified.
:param id_password: (numpy.array) Two-dimensional NumPy array where each element
is an array that contains: Id and Password
:returns: (None) The function should modify id_name_verified DataFrame in-place.
It should not return anything.
"""
password= pd.DataFrame(data=id_password[:,1],columns=["Password"])
id_name_verified = id_name_verified.join(password["Password"])
id_name_verified.drop("Verified",axis=1,inplace=True)
return id_name_verified
id_name_verified = pd.DataFrame([[1, "JohnDoe", True], [2, "AnnFranklin", False]], columns=["Id", "Login", "Verified"])
global id_name_verified
id_password = np.array([[1, 987340123], [2, 187031122]], np.int32)
login_table(id_name_verified, id_password)
print(id_name_verified)
The last print statement is still printing:
Id Login Verified
0 1 JohnDoe True
1 2 AnnFranklin False
What am I missing? I am new to python. Please help!

So instead of the join I had to use the loc function to add the password to the id_name_verified dataframe:
def login_table(id_name_verified, id_password):
password = pd.DataFrame(id_password, columns=["Id", "Password"])
id_name_verified.loc[:, 'Password'] = password['Password']
id_name_verified.drop("Verified",axis=1,inplace=True)
return None
This did the trick.

Related

groovy: convert string (which is a list) to a Groovy List

import groovy.json.JsonSlurper
def ver = "['a', 'b', 'c']"
def jsonSlurper = new JsonSlurper()
def ver_list = jsonSlurper.parseText(ver)
println ver_list
This is what I'm doing. I want to iterate over ver_list. And it seems difficult to find a solution for it.
This is the error when I print ver_list:
Caught: groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object
The current character read is ''' with an int value of 39
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 1
['a', 'b', 'c']
.^
groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object
The current character read is ''' with an int value of 39
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 1
['a', 'b', 'c']
the valid json strings must be double-quoted.
so change in your code this line and it should work:
def ver = '["a", "b", "c"]'
however if you need to parse not a valid json you could try LAX parser.
then even the following string could be parsed
import groovy.json.JsonSlurper
import groovy.json.JsonParserType
def ver = "[a, 'b', 001]"
def jsonSlurper = new JsonSlurper().setType( JsonParserType.LAX )
def ver_list = jsonSlurper.parseText(ver)
println ver_list

How to convert a CSV file to single JSON-serializable variables?

In order to automate our reporting, we want to convert Google Sheets cells to dynamic fields that we can use in a pre-written text. We think this is possible with Zapier.
We currently have the following code:
import csv
import requests
from csv import reader
result = []
url = input_data['csvlink']
stats = requests.get(url)
content = stats.content.decode('iso-8859-1')
for line in csv.reader(content.splitlines()):
result.append(line)
values = { i : result[i] for i in range(0, len(result) ) }
return values
However, this code returns a dictionary with the CSV row numbers as keys, and the data of the entire corresponding row as its value.
How can we return a dictionary with a key for every unique data point in the CSV?
Great question!
This is another case of the computer correctly doing exactly what you told it to. Namely in:
values = { i : result[i] for i in range(0, len(result) ) }
You say that values should be an dict where each key is a number and the value is the csv line at that index in the results.
In the comments, you mentioned wanting the entire CSV. Try something like:
from string import ascii_uppercase
result = {}
# your CSV code goes here. The data should be in `lines`, not `result`
for num_row, line in enumerate(lines):
for num_column, col in enumerate(line):
result[ascii_uppercase[num_column] + str(num_row + 1)] = col
return result
This will work as long as there are fewer than 26 columns. This won't do AA, AB, but that would be possible with more code if you need it.

Sorting query results with German umlaut

is there a chance to sort results of a cypher query including german umlaut like ä,ö,ü? At the moment I get a list alphabetical sorted and nodes starting with an umlaut are put at the end of the list. Normally they should be within the list e.g. an 'Ö' should be equal to 'OE'.
Any ideas are appreciated, thanks.
Since you asked specifically about Cypher, the query below is an example of how to sort umlauted characters as if they were their ligatured equivalents (e.g., treating 'Ü' as if it was 'UE').
WITH ['Dorfer', 'Dörfener'] AS names
UNWIND names AS name
RETURN name
ORDER BY
REDUCE(s = name, x IN [
['ä', 'ae'], ['Ä', 'AE'],
['ö', 'oe'], ['Ö', 'OE'],
['ü', 'ue'], ['Ü', 'UE']] |
REPLACE(s, x[0], x[1]));
The above query will return 'Dörfener' first, and 'Dorfer' second.
However, the above approach is not very efficient, since it calls the REPLACE function six times for each name. It would be much more efficient to write a user-defined procedure in Java that took the entire names list as input and returned the sorted list in a single call.
Yes, you can use localeCompare or Intl.Collator to achieve this:
// Our original array
// Outputs ["u", "x", "ü", "ü", "ü"]
const input1 = ['ü','u','ü','x','ü'];
const output1 = input1.sort();
console.log(output1);
// Intl.Collator
// Outputs ["u", "ü", "ü", "ü", "x"]
const input2 = ['ü','u','ü','x','ü'];
const output2 = input2.sort(Intl.Collator().compare);
console.log(output2)
// localeCompare
// Outputs ["u", "ü", "ü", "ü", "x"]
const input3 = ['ü','u','ü','x','ü'];
const output3 = input3.sort(function (a, b) {
return a.localeCompare(b);
});
console.log(output3)

How to read column value using grails excel import plugin?

I am using Grails excel import plugin to import an excel file.
static Map propertyConfigurationMap = [
name:([expectedType: ExcelImportService.PROPERTY_TYPE_STRING, defaultValue:null]),
age:([expectedType: ExcelImportService.PROPERTY_TYPE_INT, defaultValue:0])]
static Map CONFIG_BOOK_COLUMN_MAP = [
sheet:'Sheet1',
startRow: 1,
columnMap: [
//Col, Map-Key
'A':'name',
'B':'age',
]
]
I am able to retrieve the array list by using the code snippet:
def usersList = excelImportService.columns(workbook, CONFIG_USER_COLUMN_MAP)
which results in
[[name: Mark, age: 25], [name: Jhon, age: 46], [name: Anil, age: 62], [name: Steve, age: 32]]
And also I'm able to read each record say [name: Mark, age: 25] by using usersList.get(0)
How do I read the each column value?
I know I can read something like this
String[] row = usersList.get(0)
for (String s : row)
println s
I wonder is there any thing that plugin supports so that I can read column value directly rather manipulating it to get the desired result.
Your usersList is basically a List<Map<String, Object>> (list of maps). You can read a column using the name you gave it in the config. In your example, you named column A name and column B age. So using your iteration example as a basis, you can read each column like this:
Map row = usersList.get(0)
for(Map.Entry entry : row) {
println entry.value
}
Groovy makes this easier to do with Object.each(Closure):
row.each { key, value ->
println value
}
If you want to read a specific column value, here are a few ways to do it:
println row.name // One
println row['name'] // Two
println row.getAt('name') // Three
Hint: These all end up calling row.getAt('name')

how to sort groovy list values based on some criteria

I have one scenario to sort the values based domain class property. This property may acept all numeric and alphanumeric values in the format XXX-1.
def res= Book.listOrderByName()
or
def res = Book.findAll("from Book order by name")
Giving the same result and result is displaying first numbers latter alphanumeric values.
My problem is :
these values are sorted before -.
for example i have AB-1,AB-2,...AB-12.
The result is displayed as AB-1,AB-10.AB-11,AB-2,AB-3,..AB-9
I have result like:
[18001,18002,2,300,3901,42,9,AB-1,AB-10,AB-2,AB-21,AB-9]
It should display the value as:
[2,9,42,300,3901,18001,18002,AB-1,AB-2,AB-9,AB-10,AB-21]
Run this in the Groovy console:
List sort(list) {
list.sort {a, b ->
a.class == b.class ? a <=> b : a instanceof Integer ? -1 : 1
}
}
// Test the sort function
def list = [18001,18002,2,300,3901,42,9,'AB-1','AB-10','AB-2','AB-21','AB-9']
assert sort(list) == [2, 9, 42, 300, 3901, 18001, 18002, 'AB-1', 'AB-10', 'AB-2', 'AB-21', 'AB-9']

Resources