问题
Firstly, sorry if I have used the wrong language to explain what I'm operating on, I'm pretty new to python and still far from being knowledgeable about it.
I'm currently trying to do operations on the length of a column of data however I'm running into a few problems. These columns are from a .fit file from the 7th sdss data dump. When I run the code each value for x1, x2, x3 is printed according to the boundary conditions.
x1 = o3[(03 >= y1)]
print len(x1)
x2 = o3[(o3 < y2) & (o3 < y1)]
print len(x2)
x3 = o3[(o3 < y1) & (o3 >= y2)]
print len(x3)
xtotal = len(x1) + len(x2) + len(x3)
print xtotal
From this point I obtain values for x1, x2, x3 of around 70000, 90000 and 30000 with a total of around 190000. I would like to include a line to calculate what percentage these are of the total value however I can't seem to get this to work.
Having tried.
x1percentage = (xtotal/x1)*100
print x1percentage
This returns the elements operated on not the lengths but when i try to define the length as just a value it returns an answer of 0.
Any help would be much appreciated.
回答1:
You are probably making an error with integer math, but your statement
x1percentage = (xtotal/x1)*100
doesn't really make sense. xtotal
is an integer and x1
is an array of values, len(x1)
is an integer equal to the size of x1
, and regardless to get a percentage you would want x1/xtotal
.
If you tried len(x1)/xtotal
, you would get zero as you mentioned, because python would cast both variables as integers and use integer math, which the result is zero.
The solution cast one or both values as floats to force floating point division by
x1percentage = (xtotal / float(x1)) * 100
来源:https://stackoverflow.com/questions/35673564/operations-on-column-length