So, I have an excel spreadsheet which I want my programme to be able to access and get data from.
To do this I installed pandas and have managed to import the spreadsheet into the code.
Satellites_Path = (r'C:\Users\camer\Documents\Satellite_info.xlsx')
df = pd.read_excel(Satellites_Path, engine='openpyxl')
So this all works.
The problem is that what I want it to do is to grab a piece of data, say the distance between 2 things, and run this number through a loop. I then want it to go one down in the excel spreadsheet and do this again for the new number until there it finishes the column and then I want it to end.
The data file reads as:
Number ObjectName DistanceFromEarth(km) Radius(km) Mass(10^24kg)
0 0 Earth 0.0 6378.1 5.97240
1 1 Moon 384400.0 1783.1 0.07346
I put the 'Number' in as I thought that I could do a loop of whilst Number is < a limit then run through these numbers but I have found that the datafile doesn't work as an array or integer so that doesn't work. Since then, I have tried to put it into an integer by turning it into a NumPy array:
N = df.loc[:,'Number']
D = np.array(df.loc[:,'DistanceFromEarth(km)'])
R = np.array(df.loc[:,'Radius(km)'])
However, the arrays are still problematic. I have tried to split them up like:
a = (np.array(N))
print(a)
newa = np.array_split(a,3)
and this sort of now works but as a test, I made this little bit and it repeats infinitely:
while True:
if (newa[0]) < 1:
print(newa)
If 1 is made a 0, it prints once and then stops. I just want it to run a couple of times.
What I am getting at is, is it possible to read this file, grab a number from it and run through calculations using it, and then repeat that for the next satellite in the list? The reason I thought to do it this way is that I am going to make quite a long list. I already have a working simulation of local planets in the solar system but I wanted to add more bodies and doing it in the way that I was would make it extremely long to write, very dense and introduce more problems. Reading from a file from excel would make my life a lot easier and make it more future-proof but I don't know if it's possible and I can't see anywhere online that is similar.
CodePudding user response:
Pandas are absolutely a good choice here, but lack of knowledge of how to use them appears to be holding you back.
Here's a couple of examples that may be applicable to your situation:
- Simple row by row calculations to make a new column:
df['Diameter(km)'] = df['Radius(km)']*2
print(df)
Output:
Number ObjectName DistanceFromEarth(km) Radius(km) Mass(10^24kg) Diameter(km)
0 0 Earth 0.0 6378.1 5.97240 12756.2
1 1 Moon 384400.0 1783.1 0.07346 3566.2
- Running each row through a function:
def do_stuff(row):
print(f"Number: {row['Number']}", f"Object Name: {row['ObjectName']}")
df.apply(do_stuff, axis=1)
Output:
Number: 0 Object Name: Earth
Number: 1 Object Name: Moon