Python - For loop - run each line of output - python

I guess I am running into a beginner problem:
-> I want to loop over an array and insert the the values into lines of code that are executed.
For the attempt below I get "SyntaxError: can't assign to operator"
#Country-subsets (all countries in dataframe)
for s in country_filter:
s.lower() + '_immu_edu' = immu_edu.loc[immu_edu['CountryName'] == s]
Thanks for helping!
My expected output would be:
guinea_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "Guinea"]
lao_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "Lao PDR"]
bf_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "Burkina Faso"]
us_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "United States"]
ge_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "Germany"]

Store your values in a dictionary and access using the keys:
my_dict = dict()
for s in country_filter:
my_dict[s.lower() + '_immu_edu'] = immu_edu.loc[immu_edu['CountryName'] == s]

Related

How to update PySimpleGUI Listbox that reads an excel file

I am using python3.7 and this is the current code base(apologies for putting so much code but thought it would help overall)
def TRADE_ENTRY(df_names, df_underlyings,df_strategies, columns, param, out_path,recovery_path):
nameUpdate =0
strategyUpdate=0
underlyingUpdate=0
sg.theme('Dark Brown 1')
listing = [sg.Text(u, size = param) for u in columns]
header = [[x] for x in listing]
now = datetime.datetime.now()
core = [
sg.Input(f"{now.month}/{now.day}/{now.year}",size = param),
sg.Input(f"{now.hour}:{now.minute}:{now.second}",size = param),
sg.Listbox(list(df_strategies.STRATEGIES), size=(20,2), enable_events=False, key='_PLAYERS0_'),
sg.Listbox(['ETF', 'EQT', 'FUT', 'OPT', 'BOND'],enable_events=False,key='_PLAYERS20_',size = (20,2)),
sg.Listbox(list(df_names.NAMES), size=(20,4), enable_events=False,key='_PLAYERS6_'),
sg.Listbox( ['B', 'S'],size = (20,1),enable_events=False,key='_PLAYERS12_'),
sg.Input(size = param),
sg.Input(size = param),
sg.CalendarButton('Calendar', pad=None, font=('MS Sans Serif', 10, 'bold'),
button_color=('yellow', 'brown'), format=('%d/%m/%Y'), key='_CALENDAR_', target='_INP_'),
sg.Input(size = param),
sg.Listbox(list(df_underlyings.UNDERLYINGS), size=(20,4), enable_events=False,key='_PLAYERS2_'),
sg.Listbox(['C', 'P', 'N/A'],size = param),
]
mesh = [[x,y] for (x,y) in list(zip(listing, core))]
mesh[8].append(sg.Input(size = (10,2),key = '_INP_'))
layout =[[sg.Button("SEND"),sg.Button("NEW_NAME"), sg.Button("NEW_STRAT"), sg.Button("NEW_UND")] ]+ mesh
window = sg.Window('Trade Entry System', layout, font='Courier 12').Finalize()
while True:
event, values = window.read(timeout=500)
#print('EVENT, VALUES', event, values)# all the inputs with extra information for compiler
if event == "SEND":
data = values
a = list(data.values())
a = [x if isinstance(x, list) == False else empty_handler(x) for x in a]
a = [x if x !="" else "EMPTY" for x in a ]
#print('A', a)#all the inputs now in a list
df = pd.DataFrame(a, index = columns)
print('DF1', df)#columns dataframe with column names and then the values
df = df.transpose()
#print('DF2', df)#rows dataframe with column names and then the values
status = error_handling(df)
#print('STATUS', status)
if status == "ERROR":
print("YOU MUST RECTIFY INPUT")
elif status == "CORRECT":
#if a future then will overwrite its name
if df['TYPE'][0] == "FUT":
df['NAME'][0] = "F-"+ df['UNDERLYING'][0] + "-" +df['EXPIRATION'][0]
#if an option then will overwrite its name
elif df['TYPE'][0] =="OPT":
df['NAME'][0] = 'O-' + df['UNDERLYING'][0] + "--" + df['OPTION_TYPE'][0] +df['STRIKE'][0] +"--" +df['EXPIRATION'][0]
else:
pass
processing(df, recovery_path, out_path)
else:
print("ERROR WITH USER INPUT FATAL")
break
elif event == "NEW_NAME":
security_creation(r'Y:\NAMES.xlsx', "Sheet1", "NAME", param)
nameUpdate=1
continue
elif event == "NEW_STRAT":
security_creation(r'Y:\STRATEGIES.xlsx', "Sheet1", "STRATEGY", param)
strategyUpdate=1
continue
elif event == "NEW_UND":
security_creation(r'Y:\UNDERLYINGS.xlsx', "Sheet1", "UNDERLYINGS", param)
underlyingUpdate=1
continue
elif event == sg.TIMEOUT_KEY:
if(nameUpdate==1):
df_names = pd.read_excel(r'Y:\NAMES.xlsx', "Sheet1")
df =df_names.values.tolist()
window['_PLAYERS6_'].update(values=df, set_to_index=0)
if(underlyingUpdate==1):
df_underlyings = pd.read_excel(r'Y:\UNDERLYINGS.xlsx', "Sheet1")
df =df_underlyings.values.tolist()
window['_PLAYERS2_'].update(values=df, set_to_index=0)
if(strategyUpdate==1):
df_strategies = pd.read_excel(r'Y:\STRATEGIES.xlsx', "Sheet1")
df =df_strategies.values.tolist()
window['_PLAYERS0_'].update(values=df, set_to_index=0)
print("Listboxes updated !")
else:
print("OVER")
break
window.close()
TRADE_ENTRY(df_names, df_underlyings,df_strategies, columns, param,out_path, recovery_path)
Towards the end of the function there's 3 elif, all NEW_NAME, NEW_STRAT and NEW_UND are the user submitting information to the corresponding 3 excel files. The function security_creation actually updates said excel files. Below that I am trying to update the Listboxes but no luck.
Any help would be greatly appreciated since i am so confused

Function return empty dataframe

I would like to make a loop to create a dataframe that gathers the lines of an input dataframe, which have common points.
My problem : When I apply the function, the output dataframe is empty...
yet with a print (output) in the loop, we see that the program works .. I do not understand, i tried to change return position but that doesn't work
Thank you in advance for your help !
def group (dataframe, identifiant, output):
for i in range(len(identifiant)):
ident = identifiant.loc[i,"IDCTV"]
# print(ident)
for j in range(len(dataframe)):
if dataframe.loc[j,"IDCONTREVENANT"] == ident:
di = dataframe.loc[j, "DATE_INFRACTION"]
nt = dataframe.loc[j,"NOTRAIN"]
genre = dataframe.loc[j,"CODEETATCIVIL"]
age = dataframe.loc[j,"AGE"]
# print(di, nt, genre, age)
for k in range(len(dataframe)):
if k != j :
if dataframe.loc[k,"DATE_INFRACTION"] == di and dataframe.loc[k,"NOTRAIN"] == nt:
idgroup = dataframe.loc[k,"IDCONTREVENANT"]
genreidgroup = dataframe.loc[k,"CODEETATCIVIL"]
ageidgroup = dataframe.loc[k,"AGE"]
output = output.append({ "IDREF" : ident ,"CODEETATCIVILREF" : genre,"AGEREF" : age ,"IDCTV" : idgroup,"CODEETATCIVILCTV" : genreidgroup,"AGECTV" : ageidgroup}, ignore_index = True)
print(output)
return output
group(df,IDCTV,df_groups)
print(df_groups)
I think you want to change
group(df,IDCTV,df_groups)
to
df_groups = group(df,IDCTV,df_groups)
Right now you're calling the group funciton and doing all that calculation, but you're not saving the output anywhere. So when you run print(df_groups) it prints out whatever it was before you called the function.

Adding to JSON in Python and converting to an object

I have a JSON array shown below.
[
"3D3iAR9M4HDETajfD79gs9BM8qhMSq5izX",
"35xfg4UnpEJeHDo55HNwJbr1V3G1ddCuVA"
]
I would like to add a value in the form of the string (self.tx_amount_5) so I get a JSON OBJECT something like this:
{
"3D3iAR9M4HDETajfD79gs9BM8qhMSq5izX" : 100000
"35xfg4UnpEJeHDo55HNwJbr1V3G1ddCuVA" : 100000
}
The part of code that has generated the first JSON array is:
r = requests.get('http://api.blockcypher.com/v1/btc/main/addrs/A/balance')
balance = r.json()['balance']
with open("Entries#x1.csv") as f,open("winningnumbers.csv") as nums:
nums = set(imap(str.rstrip, nums))
r = csv.reader(f)
results = defaultdict(list)
for row in r:
results[sum(n in nums for n in islice(row, 1, None))].append(row[0])
self.number_matched_0 = results[0]
self.number_matched_1 = results[1]
self.number_matched_2 = results[2]
self.number_matched_3 = results[3]
self.number_matched_4 = results[4]
self.number_matched_5 = results[5]
self.number_matched_5_json = json.dumps(self.number_matched_5, sort_keys = True, indent = 4)
print(self.number_matched_5_json)
if len(self.number_matched_3) == 0:
print('Nobody matched 3 numbers')
else:
self.tx_amount_3 = int((balance*0.001)/ len(self.number_matched_3))
if len(self.number_matched_4) == 0:
print('Nobody matched 4 numbers')
else:
self.tx_amount_4 = int((balance*0.1)/ len(self.number_matched_4))
if len(self.number_matched_5) == 0:
print('Nobody matched 3 numbers')
else:
self.tx_amount_5 = int((balance*0.4)/ len(self.number_matched_5))
If I understand correctly, you can create the dictionary like this:
import json
s="""[
"3D3iAR9M4HDETajfD79gs9BM8qhMSq5izX",
"35xfg4UnpEJeHDo55HNwJbr1V3G1ddCuVA"
]"""
d = {el: self.tx_amount_5 for el in json.loads(s)}
print(d)
which produces
{'3D3iAR9M4HDETajfD79gs9BM8qhMSq5izX': 100000,
'35xfg4UnpEJeHDo55HNwJbr1V3G1ddCuVA': 100000}

how to skip a value while printing from dict, if the value is blank

I have a dict
x4={'c;1': 'c4;;c6', 'b;1': 'a2;b2;c2;d2', 'b;0': 'A1;B1;C1;D1', 'a;1': 'a1;b1;c1;d1', 'a;0': 'A;B;C;D', 'c;0': 'c1;c2;c3'}
i am using this code:
for k,v in x4.iteritems():
a = k.split(";")
b = v.split(";")
if a[1] is not '0':
val = x4[a[0]+';0']
values = val.split(";")
for i in range(len(values)):
if values[i]=='' is True:
b[i]=''
else:
print '<%s>%s<%s>' % (values[i],b[i],values[i])
output its printing is
<c1>c4<c1>
<c2><c2>
<c3>c6<c3>
<A1>a2<A1>
<B1>b2<B1>
<C1>c2<C1>
<D1>d2<D1>
<A>a1<A>
<B>b1<B>
<C>c1<C>
<D>d1<D>
But What i want is
<c1>c4<c1>
<c3>c6<c3>
<A1>a2<A1>
<B1>b2<B1>
<C1>c2<C1>
<D1>d2<D1>
<A>a1<A>
<B>b1<B>
<C>c1<C>
<D>d1<D>
The 'c2' should not be printed.. I am using this code to print grouped data. pls help me
x4={'c;1': 'c4;;c6', 'b;1': 'a2;b2;c2;d2', 'b;0': 'A1;B1;C1;D1', 'a;1': 'a1;b1;c1;d1', 'a;0': 'A;B;C;D', 'c;0': 'c1;c2;c3'}
for k,v in x4.iteritems():
a = k.split(";")
b = v.split(";")
if a[1] is not '0':
val = x4[a[0]+';0']
values = val.split(";")
for i in range(len(values)):
if values[i] is '':
b[i]=''
else:
if b[i]:
print '<%s>%s<%s>' % (values[i],b[i],values[i])
output::
<A1>a2<A1>
<B1>b2<B1>
<C1>c2<C1>
<D1>d2<D1>
<c1>c4<c1>
<c3>c6<c3>
<A>a1<A>
<B>b1<B>
<C>c1<C>
<D>d1<D>

Learning Python: Store values in dict from stdout

How can I do the following in Python:
I have a command output that outputs this:
Datexxxx
Clientxxx
Timexxx
Datexxxx
Client2xxx
Timexxx
Datexxxx
Client3xxx
Timexxx
And I want to work this in a dict like:
Client:(date,time), Client2:(date,time) ...
After reading the data into a string subject, you could do this:
import re
d = {}
for match in re.finditer(
"""(?mx)
^Date(.*)\r?\n
Client\d*(.*)\r?\n
Time(.*)""",
subject):
d[match.group(2)] = (match.group(1), match.group(2))
How about something like:
rows = {}
thisrow = []
for line in output.split('\n'):
if line[:4].lower() == 'date':
thisrow.append(line)
elif line[:6].lower() == 'client':
thisrow.append(line)
elif line[:4].lower() == 'time':
thisrow.append(line)
elif line.strip() == '':
rows[thisrow[1]] = (thisrow[0], thisrow[2])
thisrow = []
print rows
Assumes a trailing newline, no spaces before lines, etc.
What about using a dict with tuples?
Create a dictionary and add the entries:
dict = {}
dict['Client'] = ('date1','time1')
dict['Client2'] = ('date2','time2')
Accessing the entires:
dict['Client']
>>> ('date1','time1')

Categories