In: Computer Science
Need to replace the 0's in Bid/Ask column with "Bid" and the 1's with "Ask" using Python.
For line in lines:
line = line.replace(",0,","Bid") etc did not work
Time,Bid\Ask,Price,Volume 05:08.627012,0,1.16198,10000000.0 05:08.627012,1,1.16232,10000000.0 05:08.627012,0,1.16198,10000000.0 05:12.721536,0,1.16209,1000000.0 05:08.627012,1,1.16232,10000000.0 05:08.627012,0,1.16198,10000000.0 05:12.721536,0,1.16209,1000000.0 05:12.729989,1,1.16218,1000000.0 05:08.627012,1,1.16232,10000000.0 05:08.627012,0,1.16198,10000000.0 05:12.735727,0,1.16208,1000000.0 05:12.729989,1,1.16218,1000000.0 05:08.627012,1,1.16232,10000000.0
PROGRAM :
# lines from the question
lines = ["05:08.627012,0,1.16198,10000000.0" ,
"05:08.627012,1,1.16232,10000000.0" ,
"05:08.627012,0,1.16198,10000000.0" ,
"05:12.721536,0,1.16209,1000000.0" ,
"05:08.627012,1,1.16232,10000000.0" ,
"05:08.627012,0,1.16198,10000000.0" ,
"05:12.721536,0,1.16209,1000000.0" ,
"05:12.729989,1,1.16218,1000000.0" ,
"05:08.627012,1,1.16232,10000000.0" ,
"05:08.627012,0,1.16198,10000000.0" ,
"05:12.735727,0,1.16208,1000000.0" ,
"05:12.729989,1,1.16218,1000000.0" ,
"05:08.627012,1,1.16232,10000000.0"]
# bid_ask(x) function which returns "Bid" if value is 0 or else "Ask"
def bid_ask(x):
if x=='0':
return "Bid"
elif x=='1':
return "Ask"
# new_lines to store the replaced list
new_lines = []
# iterating the lines list
for line in lines :
# splitting using comma operator and store it as a list
split_list = line.split(',')
# replacing the Bid/Ask column with the respective values by calling bid_ask function
split_list[1] = bid_ask(split_list[1])
# joining back the list items which we split in the previous steps in the same format using comma operator
temp_string = ','.join(split_list)
# appending the strings to a new list
new_lines.append(temp_string)
print("The original list is :")
print(lines)
print("\nThe modified list is :")
print(new_lines)

OUTPUT:
