Python dataframe if if if - pandas

Why does my code not run when option2 is 1?
option2 = ""
specificReport = "yes"
if specificReport == "yes":
specificReport = str.lower(input("Do you want to look at the specific report (yes/no) : " ))
option2 = str.lower(input("Which data are you looking for \
(1. Location, 2. Type of Risk, 3. Risk Level , 4. Date & Time): "))
if option2 == 1:
locationValue = input('Enter the location you want to inspect: ')
LocationRow = (dataframe.loc[dataframe['Location Name'] == locationValue])
print(locationRow)

Because the output of input is a string, so you compare option2 (a string) with 1 (an integer). Either you convert the integer to string (i.e., '1' instead of 1) or you convert the output of input to an integer (i.e., int(option2)).

Because it's a string. You need to make it an int
if int(option2) == 1.
Also you don't really need str.lower() on the input - you can make in int() from there too.

Related

Numpy.selectand assign new colum in df with condition from values of two column

df = df.assign[test = np.select[df.trs = 'iw' & df.rp == 'yu'],[1,0],'null']
I want if df.trs == iw' and df.rp == 'yu'` than new column should be created should be 0 else 1 only for condotion fullfilling row not every row
I tried no.slect and with condition array. But not getting desired output
You don't need numpy.select, a simple boolean operator is sufficient:
df['test'] = (df['trs'].eq('iw') & df['rp'].eq('yu')).astype(int)
If you really want to use numpy, this would require numpy.where:
df['test'] = np.where(df['trs'].eq('iw') & df['rp'].eq('yu'), 1, 0)

Simple Beginner Loop Wont Close

Practicing some stuff and I've been way beyond this simple of a concept but this loop won't close and I can't understand why.
ans = "Y"
while ans == "Y" or "y":
num = int(input("What's your number? "))
if num % 2 == 0:
print("That number is even!\n")
else:
print("That number is odd!\n")
ans = str(input("Do you have another number, Y/y or N/n? "))
So I declare the variable first so I can enter the loop then ask for it again on the tail side to close it out...but no matter what I enter it continues.
I'm sure it's simple like I said i'm way past this kind of thing but it won't close and I'm not sure what the issue is?
The problem lies in the 'or "y"':
You should check if ans is Y or y which is correctly expressed as 'ans == "Y" or ans == "y"'
You as well needs to specify a starting condition for ans.
ans = "y"
while ans == "Y" or ans == "y":
num = int(input("What's your number? "))
if num % 2 == 0:
print("That number is even!\n")
else:
print("That number is odd!\n")
ans = str(input("Do you have another number, Y/y or N/n? "))

How to convert text lines to variables?

Check out this list. I need each one turned into a variable and set equal to 0. Example:
;1-Methyoxy-2-Propanol would be:
$OneMethoxyTwoPropanol = 0
;and 1,2-BUTADIENE would be:
$OneTwoButadiene = 0
Assigning them to a variable wouldn't be a problem, but there are 1500 of them.
If i had to do this work i'll make it this way :
I'll change the case of each word :
Regex to change to sentence case
Make a "SearchAndReplace" :
1 -> One
2 -> Two
...
{underscore} -> ''
{space} -> ''
...
Then in a soft like SublimeText i'll add a $ in front of each line and a = 0 at the end. With the help of the Ctrl+Shift+L
Maybe you could use a regex to help you in the "SearchAndReplace" thing.
Something like this?
Local $sFilePath = #DesktopDir & "\test.ini"
Local $aArray = IniReadSection($sFilePath, "Variables")
Local $aVariablesArray[UBound($aArray)][2]
For $i = 1 To $aArray[0][0]
$aVariablesArray[$i][0] = $aArray[$i][0]
$aVariablesArray[$i][1] = $aArray[$i][1]
Next
For $i = 1 To UBound($aVariablesArray) -1
MsgBox(0, "", "Variable: " & $aVariablesArray[$i][0] & #CRLF & "Value: " & $aVariablesArray[$i][1])
Next
Your ini file should look like this
[Variables]
firstvariable=0
secondvariable=0
etc...=0
To create an ini file just open notepad, write down the file and then save it as .ini.
You can use RegEx to rename each file according to your needs.
The array created is a 2d array. It is needed to store the variable's name and value.
stringreplace and assign will do the job. If the amount of number to word replacements becomes too large you may consider storing those rather than nesting replace functions.
$sStr = "1-Methyoxy-2-Propanol" & #LF & "1,2-BUTADIENE"
$sStr = stringreplace(stringreplace(stringreplace(stringreplace($sStr , "," , "-") , "1-" , "One") , "2-" , "Two") , "-" , "")
$aStr = stringsplit($sStr , #LF , 2)
For $i = 0 to ubound($aStr) - 1
Assign($aStr[$i] , 0)
Next
msgbox(0, '' , Eval("OneMethyoxyTwoPropanol") & #LF & Eval("OneTwoBUTADIENE"))
I simply need to turn them into a variable and set them equal to 0.
As per Documentation - Intro - Arrays:
An Array is a variable containing a series of data elements. Each element in this variable can be accessed by an index number which relates to the position of the element within the Array - in AutoIt the first element of an Array is always element [0]. Arrays elements are stored in a defined order and can be sorted.
Removes lines containing list names (; List I etc.) and empty (or less than three character-) lines (as per $g_sRegexFilter). Stores remaining lines to 2D array-elements. Example:
#include <StringConstants.au3>
#include <FileConstants.au3>
#include <Array.au3>
Global Enum $ITEM_NAME, _
$ITEM_VALUE
Global Const $g_sFilePath = 'C:\list.txt'
Global Const $g_sFileNewline = #CRLF
Global Const $g_sRegexFilter = '(?m)^(.{0,2}\v)|(;.*\v)$'
Global Const $g_sItemHeader = 'name|value'
Global $g_sFileText = ''
Global $g_aFileItems
$g_sFileText = _TextFromFile($g_sFilePath)
$g_sFileText = StringRegExpReplace($g_sFileText, $g_sRegexFilter, '')
$g_aFileItems = StringSplit($g_sFileText, $g_sFileNewline, $STR_ENTIRESPLIT + $STR_NOCOUNT)
_ArrayColInsert($g_aFileItems, $ITEM_VALUE)
For $i1 = 0 To UBound($g_aFileItems) - 1
$g_aFileItems[$i1][$ITEM_VALUE] = 0
Next
_ArrayDisplay($g_aFileItems, '$g_aFileItems', '', 0, Default, $g_sItemHeader)
Func _TextFromFile(Const $sFile)
Local $hFile = FileOpen($sFile, $FO_READ + $FO_UTF8_NOBOM)
Local Const $sData = FileRead($hFile)
FileClose($hFile)
Return $sData
EndFunc
Returns:
1-Methoxy-2-Propanol | 0
1,2-BUTADIENE | 0
2-Diethyl aminoethanol | 0
2-ETHYL HEXANOL | 0
2-ETHYL HEXYL ACRYLATE | 0
2-Ethyl hexyl lights | 0
2-Ethyl phenol | 0
2-Ethylsuccionitrile | 0
2-Methyl piperidine | 0
2-Methyl-2-Butene nitrile | 0
2-Methyl-2-Pentenal | 0
2-Methyl-3-Butene nitrile | 0
2-Methylglutaronitrile | 0
...
As:
$g_aFileItems[ x ][$ITEM_NAME]
$g_aFileItems[ x ][$ITEM_VALUE]
Add additional columns using _ArrayColInsert().
... as there are 1500 of them.
Consider using SQLite. Related.
I am using Notepad++, so I'm not sure if this would work with any other IDEs/Notepads. I'm going to be using 1-Methoxy-2-Propanol for my following example.
I learned not to start variables with numbers, so I needed to replace them with words. 1-Methoxy-2-Propanol contains a 1 and a 2, we need to change these to One and Two.
Starting product:
1-Methoxy-2-Propanol
Press Ctrl + F and move to the replace tab. In the "Find what:" box, type 1. In the "Replace with:" box, type One, then press "replace all" (not just "replace"). Do this for numbers zero (0) through nine (9). Now, your product will look like this:
One-Methoxy-Two-Propanol
Next we need to get rid of the dashes. In the Replace tab, inside of the "Find what:" box, type - and in the "Replace With:" box, backspace completely so there is nothing there, then press "Replace All". Now, your product will look like this:
OneMethoxyTwoPropanol
There are other products that include comas and parenthesis, so simply find and replace these like above.
We need to add $ to the beginning of each word. Press Ctrl + F again and go to the Replace tab. In the "Find what:" box, type ^ which symbolizes the start of a new line. In the "Replace with:" box, type $ and press "Replace All". This will make your product look like:
$OneMethoxyTwoPropanol
We need to set all of these variables zero! Go back to the replace tab. In the "Find what:" box type \r. In the "Replace with:" box, type = 0. Note the space before the equal sign. Press "Replace All". Your product will look like this:
$OneMethoxyTwoPropanol = 0
Your file should have started like this:
1-Methoxy-2-Propanol
1,2-BUTADIENE
2-Diethyl aminoethanol
2-ETHYL HEXANOL
2-ETHYL HEXYL ACRYLATE
2-Ethyl hexyl lights
2-Ethyl phenol
2-Ethylsuccionitrile
2-Methyl piperidine
2-Methyl-2-Butene nitrile
2-Methyl-2-Pentenal
2-Methyl-3-Butene nitrile
2-Methylglutaronitrile
2-Pentene nitrile
2,4,7,9-Tetramethyl-5-decyne-4
And ended up like this:
$OneMethoxyTwoPropanol = 0
$OneTwoBUTADIENE = 0
$TwoDiethylaminoethanol = 0
$TwoETHYLHEXANOL = 0
$TwoETHYLHEXYLACRYLATE = 0
$TwoEthylhexyllights = 0
$TwoEthylphenol = 0
$TwoEthylsuccionitrile = 0
$TwoMethylpiperidine = 0
$TwoMethylTwoButenenitrile = 0
$TwoMethylTwoPentenal = 0
$TwoMethylThreeButenenitrile = 0
$TwoMethylglutaronitrile = 0
$TwoPentenenitrile = 0
$TwoFourSevenNineTetramethylFivedecyneFour = 0

Lua table.toString(tableName) and table.fromString(stringTable) functions?

I am wanting to convert a 2d lua table into a string, then after converting it to a string convert it back into a table using that newly created string. It seems as if this process is called serialization, and is discussed in the below url, yet I am having a difficult time understanding the code and was hoping someone here had a simple table.toString and table.fromString function
http://lua-users.org/wiki/TableSerialization
I am using the following code in order to serialize tables:
function serializeTable(val, name, skipnewlines, depth)
skipnewlines = skipnewlines or false
depth = depth or 0
local tmp = string.rep(" ", depth)
if name then tmp = tmp .. name .. " = " end
if type(val) == "table" then
tmp = tmp .. "{" .. (not skipnewlines and "\n" or "")
for k, v in pairs(val) do
tmp = tmp .. serializeTable(v, k, skipnewlines, depth + 1) .. "," .. (not skipnewlines and "\n" or "")
end
tmp = tmp .. string.rep(" ", depth) .. "}"
elseif type(val) == "number" then
tmp = tmp .. tostring(val)
elseif type(val) == "string" then
tmp = tmp .. string.format("%q", val)
elseif type(val) == "boolean" then
tmp = tmp .. (val and "true" or "false")
else
tmp = tmp .. "\"[inserializeable datatype:" .. type(val) .. "]\""
end
return tmp
end
the code created can then be executed using loadstring(): http://www.lua.org/manual/5.1/manual.html#pdf-loadstring if you have passed an argument to 'name' parameter (or append it afterwards):
s = serializeTable({a = "foo", b = {c = 123, d = "foo"}})
print(s)
a = loadstring(s)()
The code lhf posted is a much simpler code example than anything from the page you linked, so hopefully you can understand it better. Adapting it to output a string instead of printing the output looks like:
t = {
{11,12,13},
{21,22,23},
}
local s = {"return {"}
for i=1,#t do
s[#s+1] = "{"
for j=1,#t[i] do
s[#s+1] = t[i][j]
s[#s+1] = ","
end
s[#s+1] = "},"
end
s[#s+1] = "}"
s = table.concat(s)
print(s)
The general idea with serialization is to take all the bits of data from some data structure like a table, and then loop through that data structure while building up a string that has all of those bits of data along with formatting characters.
How about a JSON module? That way you have also a better exchangeable data. I usually prefer dkjson, which also supports utf-8, where cmjjson won't.
Under the kong works this
local cjson = require "cjson"
kong.log.debug(cjson.encode(some_table))
Out of the kong should be installed package lua-cjson https://github.com/openresty/lua-cjson/
Here is a simple program which assumes your table contains numbers only. It outputs Lua code that can be loaded back with loadstring()(). Adapt it to output to a string instead of printing it out. Hint: redefine print to collect the output into a table and then at the end turn the output table into a string with table.concat.
t = {
{11,12,13},
{21,22,23},
}
print"return {"
for i=1,#t do
print"{"
for j=1,#t[i] do
print(t[i][j],",")
end
print"},"
end
print"}"
Assuming that:
You don't have loops (table a referencing table b and b referencing a)
Your tables are pure arrays (all keys are consecutive positive integers, starting on 1)
Your values are integers only (no strings, etc)
Then a recursive solution is easy to implement:
function serialize(t)
local serializedValues = {}
local value, serializedValue
for i=1,#t do
value = t[i]
serializedValue = type(value)=='table' and serialize(value) or value
table.insert(serializedValues, serializedValue)
end
return string.format("{ %s }", table.concat(serializedValues, ', ') )
end
Prepend the string resulting from this function with a return, store it on a .lua file:
-- myfile.lua
return { { 1, 2, 3 }, { 4, 5, 6 } }
You can just use dofile to get the table back.
t = dofile 'myfile.lua'
Notes:
If you have loops, then you will have
to handle them explicitly - usually with an extra table to "keep track" of repetitions
If you don't have pure arrays, then
you will have to parse t differently,
as well as handle the way the keys are rendered (are they strings? are they other tables? etc).
If you have more than just integers
and subtables, then calculating
serializedValue will be more
complex.
Regards!
I have shorter code to convert table to string but not reverse
function compileTable(table)
local index = 1
local holder = "{"
while true do
if type(table[index]) == "function" then
index = index + 1
elseif type(table[index]) == "table" then
holder = holder..compileTable(table[index])
elseif type(table[index]) == "number" then
holder = holder..tostring(table[index])
elseif type(table[index]) == "string" then
holder = holder.."\""..table[index].."\""
elseif table[index] == nil then
holder = holder.."nil"
elseif type(table[index]) == "boolean" then
holder = holder..(table[index] and "true" or "false")
end
if index + 1 > #table then
break
end
holder = holder..","
index = index + 1
end
return holder.."}"
end
if you want change the name just search all compileTable change it to you preferred name because this function will call it self if it detect nested table but escape sequence I don't know if it work
if you use this to create a lua executable file that output the table it will ge compilation error if you put new line and " sequence
this method is more memory efficient
Note:
Function not supported
User data I don't know
My solution:
local nl = string.char(10) -- newline
function serialize_list (tabl, indent)
indent = indent and (indent.." ") or ""
local str = ''
str = str .. indent.."{"
for key, value in pairs (tabl) do
local pr = (type(key)=="string") and ('["'..key..'"]=') or ""
if type (value) == "table" then
str = str..nl..pr..serialize_list (value, indent)..','
elseif type (value) == "string" then
str = str..nl..indent..pr..'"'..tostring(value)..'",'
else
str = str..nl..indent..pr..tostring(value)..','
end
end
str = str:sub(1, #str-1) -- remove last symbol
str = str..nl..indent.."}"
return str
end
local str = serialize_list(tables)
print('return '..nl..str)

How to define a 2-Column Array A = 1, B = 2... ZZZ =?

I need to create a 2 column array in ABAP so that a program can look up a record item (defined by the letters A - ZZZ) and then return the number associated with it.
For example:
A = 1
B = 2
C = 3
...
Z = 26
AA = 27
AB = 28
...
AZ =
BA =
...
BZ =
CA =
...
...
ZZZ =
Please can you suggest how I can code this.
Is there a better option than writing an array?
Thanks.
you don't need to lookup the value in a table. this can be calculated:
parameters: p_input(3) type c value 'AAA'.
data: len type i value 0,
multiplier type i value 1,
result type i value 0,
idx type i.
* how many characters are there?
len = strlen( p_input ).
idx = len.
* compute the value for every char starting at the end
* in 'ABC' the C is multiplied with 1, the B with 26 and the A with 26^2
do len times.
* p_input+idx(1) should be the actual character and we look it up in sy-abcde
search p_input+idx(1) in SY-ABCDE.
* if p_input+idx(1) was A then sy-fdpos should now be set to 0 that is s why we add 1
compute result = result + ( sy-fdpos + 1 ) * multiplier.
idx = idx - 1.
multiplier = multiplier * 26.
enddo.
write: / result.
i didn't test the program and it has pretty sure some syntax errors. but the algorithm behind it should work.
perhaps I'm misunderstanding, but don't you want something like this?
type: begin of t_lookup,
rec_key type string,
value type i,
end of t_lookup.
data: it_lookup type hashed table of t_lookup with unique key rec_key.
then once it's populated, read it back
read table it_lookup with key rec_key = [value] assigning <s>.
if sy-subrc eq 0.
" got something
else.
" didn't
endif.
unfortunately, arrays don't exist in ABAP, but a hashed table is designed for this kind of lookup (fast access, unique keys).
DATA: STR TYPE STRING, I TYPE I, J TYPE I, K TYPE I, CH TYPE C, RES
TYPE INT2, FLAG TYPE I.
PARAMETERS: S(3).
START-OF-SELECTION.
I = STRLEN( S ).
STR = S.
DO I TIMES.
I = I - 1.
CH = S.
IF CH CO '1234567890.' OR CH CN SY-ABCDE.
FLAG = 0.
EXIT.
ELSE.
FLAG = 1.
ENDIF.
SEARCH SY-ABCDE FOR CH.
J = I.
K = 1.
WHILE J > 0.
K = K * 26.
J = J - 1.
ENDWHILE.
K = K * ( SY-FDPOS + 1 ).
RES = RES + K.
REPLACE SUBSTRING CH IN S WITH ''.
ENDDO.
* RES = RES + SY-FDPOS.
IF FLAG = 0.
MESSAGE 'String is not valid.' TYPE 'S'.
ELSE.
WRITE: /, RES .
ENDIF.
Use this code after executing.
I did a similar implementation some time back.
Check this it it works for you.
DATA:
lv_char TYPE char1,
lv_len TYPE i,
lv_len_minus_1 TYPE i,
lv_partial_index1 TYPE i,
lv_partial_index2 TYPE i,
lv_number TYPE i,
result_tab TYPE match_result_tab,
lv_col_index_substr TYPE string,
lv_result TYPE i.
FIELD-SYMBOLS:
<match> LIKE LINE OF result_tab.
lv_len = strlen( iv_col_index ) .
lv_char = iv_col_index(1).
FIND FIRST OCCURRENCE OF lv_char IN co_char RESULTS result_tab.
READ TABLE result_tab ASSIGNING <match> INDEX 1.
lv_number = <match>-offset .
lv_number = lv_number + 1 .
IF lv_len EQ 1.
ev_col = ( ( 26 ** ( lv_len - 1 ) ) * lv_number ) .
ELSE.
lv_len_minus_1 = lv_len - 1.
lv_col_index_substr = iv_col_index+1(lv_len_minus_1) .
CALL METHOD get_col_index
EXPORTING
iv_col_index = lv_col_index_substr
IMPORTING
ev_col = lv_partial_index2.
lv_partial_index1 = ( ( 26 ** ( lv_len - 1 ) ) * lv_number ) + lv_partial_index2 .
ev_col = lv_partial_index1 .
ENDIF.
Here The algorithm uses a recursive logic to determine the column index in numbers.
This is not my algorithm but have adapted to be used in ABAP.
The original algorithm is used in Open Excel, cant find any links right now.