Python2: Convert a set of floats to a string - python-2.7

Question
The goal is to find a simple way for converting a set of data to a string.
Maybe I am too newby but I found nothing about conversion from a set to string. A similar question (Numpy converting array from float to strings) did not help me a lot.
Example
The code I wrote seems definitely not ideal:
DataSet = {(1,4): 272.3,
(2,4): 274.74}
print(', '.join(np.array(DataSet).astype('str'))))
Personal goal
In the end I want to create a string like:
DataSet = {(1,4): 272.3,
(2,4): 274.74}
version = 2.7
print(''.join(np.array(['The data in {',
', '.join(np.array(DataSet).astype('str'))),
'} is calculated with python%3.1f.' % version]))
The output should look like (it would be nice but not necessary to implement some fixed float precision):
'The data in {272.3, 274.7} is calculated with python2.7.'

DataSet is a Python dictionary and thus DataSet.values() returns the list of its values.
The string you need can be generated by ', '.join(map(str, DataSet.values())) or ', '.join(str(v) for v in DataSet.values()).

Related

How to convert list into DataFrame in Python (Binance Futures API)

Using Binance Futures API I am trying to get a proper form of my position regarding cryptocurrencies.
Using the code
from binance_f import RequestClient
request_client = RequestClient(api_key= my_key, secret_key=my_secet_key)
result = request_client.get_position()
I get the following result
[{"symbol":"BTCUSDT","positionAmt":"0.000","entryPrice":"0.00000","markPrice":"5455.13008723","unRealizedProfit":"0.00000000","liquidationPrice":"0","leverage":"20","maxNotionalValue":"5000000","marginType":"cross","isolatedMargin":"0.00000000","isAutoAddMargin":"false"}]
The type command indicates it is a list, however adding at the end of the code print(result) yields:
[<binance_f.model.position.Position object at 0x1135cb670>]
Which is baffling because it seems not to be the list (in fact, debugging it indicates object of type Position). Using PrintMix.print_data(result) yields:
data number 0 :
entryPrice:0.0
isAutoAddMargin:True
isolatedMargin:0.0
json_parse:<function Position.json_parse at 0x1165af820>
leverage:20.0
liquidationPrice:0.0
marginType:cross
markPrice:5442.28502271
maxNotionalValue:5000000.0
positionAmt:0.0
symbol:BTCUSDT
unrealizedProfit:0.0
Now it seems like a JSON format... But it is a list. I am confused - any ideas how I can convert result to a proper DataFrame? So that columns are Symbol, PositionAmt, entryPrice, etc.
Thanks!
Your main question remains as you wrote on the header you should not be confused. In your case you have a list of Position object, you can see the structure of Position in the GitHub of this library
Anyway to answer the question please use the following:
df = pd.DataFrame([t.__dict__ for t in result])
For more options and information please read the great answers on this question
Good Luck!
you can use that
df = pd.DataFrame([t.__dict__ for t in result])
klines=df.values.tolist()
open = [float(entry[1]) for entry in klines]
high = [float(entry[2]) for entry in klines]
low = [float(entry[3]) for entry in klines]
close = [float(entry[4]) for entry in klines]

Get information from a TXT File

I have a txt file that has 7 columns and I am trying to extract data from. Essentially there is a column that has a lot of minimum values, a column solely consists of dashes, column of only maximum values, and a few others that I would like to break into their own lists (I think thats the way to go). Any help would be much appreciated. Thanks!
Edit: Sorry I should have been clearer. I am using Python 3.5, grabbing right from the txt and using split actually. I guess I should ask where to go from there. I currently have it loading a file and using split(). End game I would like to be able to put each column into its own list so I can calculate averages, percentages, etc. Thanks again, sorry about the bad initial post, its my first time posting here.
file = open("year2000.txt")
for line in file:
z = line.strip()
z = line.find(" ")
min_sal1 = line[:z]
min_sal2 = min_sal1.replace(',', '')
min_sal3 = min_sal2.find('.')
min_sal4 = min_sal1[:min_sal3]
min_sal = int(min_sal4)
print(min_sal4)
y = z.find(' ', 2)
x = z.find(' ', 3)
max_sal = line[y:x]
print(max_sal)
After running this, I get a list of all min salarys like it should, however for max values I am getting just a bunch of blank lines. I also plan on putting each type of value into their own lists. Thanks

How to transfer covariance-like table into one-to-one pairs cleverly in stata?

I encounter a practical issue on data management using Stata. What I'm planning to do is creating variable of spherical distances between 30 province capitals (so there are roughly 870 identical values) of China. There have been some user-written commands to handle this issue(through google map) but My problem is, for some confidential reason, the data is stored in a isolated computer that disconnected to internet,so I have to defined all of the one-to-one distance value in do-file and then merge them into the data. Given the nontrival workload (though not really infeasible), I wonder if there is some clever way to do the job. I have an excel worksheet in which the distance is like a covariance martrix with province capitals' names appearing in both first row and column,it's like a lower-triangle matrix, . stands for values
A B C D E AD
capital_1 capital_2 capital_3 capital_4 ······ capital_30
1 capital_1
2 capital_2 '
3 capital_3 ' '
4 capital_4 ' ' '
········
capital_30 ' ' ' '
I know how to import such martrix, but can I generate the desired one-to-one pairs? Thank you.
Thanks for #Roberto 's helpful suggestion, I have partly solved the problem, and I pose my solution to benefit any newcomer who may meet similar problem, and want to benefit from the real experts to improve my code
//import data from excel file
import excel using distance.xls
*********************************
* rename the variable name
* (to make it more well orgnized to facilitie use of --reshape-- command
*********************************
* rename the first column
ren A id
* rename the following variables
local i=0
foreach var of varlist B-AF {
local j=`i'+1
local i=`i'+1
ren `var' distance`j'
}
*********************************
* reshape the data
*********************************
reshape long distance,i(id) j(city)
tostring city,replace
***the following part is really urgly, because I don't know how
*to gen a one-to-one mapping between orginal province name and
*the new generated variable name like distance`j',I have to recover
*them by hand, I hope someone can help me to improve this part**
replace city="北京" if city=="1"
replace city="天津" if city=="2"
replace city="河北" if city=="3"
replace city="山西" if city=="4"
replace city="内蒙古" if city=="5"
replace city="辽宁" if city=="6"
replace city="吉林" if city=="7"
·····

IO for julia reading fortran files

Noob question:
I have the output of a complex matrix done in Fortran, the contents looks like this:
(-0.594209719263636,1.463867815703586E-006)
(-0.783378034185788,-0.182301028756558) (-0.794024313844809,0.128219337674814)
(0.592814294881930,4.069892201461069E-002)
I want to read and use this data in a julia program.
No, I don't want to change the writting format, I would like to learn how to strip off
the "trash" characters like '(', or ','. This may be useful for arbitrary Input files.
2.I have tried with the following code:
file = open(pathtofilename, "r")
data_str = readall(ifile)
data_numbers_str = split(data_str)
data_numbers = split(data_numbers_str, ['('])
However, the manual is not quite self-explanatory [http://docs.julialang.org/en/release-0.2/stdlib/base/?highlight=split].
Here is what I'd do
data = "(-0.594209719263636,1.463867815703586E-006) (-0.783378034185788,-0.182301028756558) (-0.794024313844809,0.128219337674814) (0.592814294881930,4.069892201461069E-002)"
function pair_to_complex(pair)
nums = float(split(pair[2:end-1], ","))
return Complex(nums...)
end
numbers = map(pair_to_complex, split(data, " "))
To explain
The pair[2:end-1] removes the parenthesis
I then split that on the , to get an array with two numbers, still as strings
I convert them to Float64 with float(), obtaining an array of floats
I make a new complex number. The ... splats the array out so it provides the two arguments to Complex - I could have done Complex(nums[1],nums[2])
I then apply this logic using map to every term in the data.

Stata: Efficient way to replace numerical values with string values

I have code that currently looks like this:
replace fname = "JACK" if id==103
replace lname = "MARTIN" if id==103
replace fname = "MICHAEL" if id==104
replace lname = "JOHNSON" if id==104
And it goes on for multiple pages like this, replacing an ID name with a first and last name string. I was wondering if there is a more efficient way to do this en masse, perhaps by using the recode command?
I will echo the other answers that suggest a merge is the best way to do this.
But if you absolutely must code the lines item-wise (again, messy) you can generate a long list ("pages") of replace commands by using MS Excel to "help" you write the code. Here is a picture of your Excel sheet with one example, showing the MS Excel formula:
columns:
A B C D
row: 1 last first id code
2 MARTIN JACK 103 ="replace fname=^"&B2&"^ if id=="&C2
You type that in, make sure it looks like Stata code when the formula calculates (aside from the carets), and copy the formula in column D down to the end of your list. Then copy the whole block of Stata code in column D generated by the formulas into your do-file, and do a find and replace (be careful here if you are using the caret elsewhere for mathematical uses!!) for all ^ to be replaced with ", which will end up generating proper Stata syntax.
(This is truly a brute force way of doing this, and is less dynamic in the case that there are subsequent changes to your generation list. All--apologies in advance for answering a question here advocating use of Excel :) )
You don't explain where the strings you want to add come from, but what is generally the best technique is explained at
http://www.stata.com/support/faqs/data-management/group-characteristics-for-subsets/index.html
Create an associative array of ids vs Fname,Lname
103 => JACK,MARTIN
104 => MICHAEL,JOHNSON
...
Replace
id => hash{id} ( fname & lname )
The efficiency of doing this will be taken care by the programming language used