Use column to name python file

Viewed 32

I have the following code which gives me alternating random results like this:

LOCATION DIRECTION SPEED
Ring 110 1.52

OR

LOCATION LEVEL (M)
Tivoli 3.97
import pandas as pd
import random
from datetime import datetime
import os

wind_list = ['Ring', 'Tbreedy']
tide_list = ['Cobh', 'Tivoli']

df = pd.DataFrame(data={'LOCATION':str(random.choice(wind_list)),'LAST UPDATE':str(datetime.now()),'DIRECTION':str(random.randint(100,200)),'SPEED':str(random.random()+random.randint(1,5))[:4]},index=[0])

df2 = pd.DataFrame(data={'LOCATION':str(random.choice(tide_list)),'LAST UPDATE':str(datetime.now()),'LEVEL(M)':str(random.random()+random.randint(2,5))[:4]},index=[0])

testlist = [df, df2]
testlist2 = random.choice(testlist)
print(testlist2)

The purpose of this is to upload the result to an S3 bucket and trigger a lambda function. However, this is where my issue lies. Is there a way to write the output result from print(testlist2) to a CSV file where I name the CSV file something like SENSOR _____.csv where the ___ is the location which has been provided in the output?

Essentially, each time the code is ran a different location is provided, so I would like to extract the given location and place it in the CSV file name. I also don't want the LOCATION column within my CSV - I need this column dropped, as it's only purpose is to be in the file name.

1 Answers

Is that what you are looking for?

location = testlist2.loc[0,'LOCATION']
testlist2.drop(['LOCATION'], axis=1).to_csv(f'SENSOR {location}.csv')
Related