pawan
pawan

Reputation: 21

how can I rewrite this code to make it easier to read?

start=2014
df = pd.DataFrame({'age':past_cars_sold,}, index = [start, start+1,start+2,start+3,start+4,start+5,start+6])

is there an easier way to rewrite this code. Right now i have do it one at a time and just want to know if there is an easier way to rewrite this.

Upvotes: 2

Views: 85

Answers (2)

James Newman
James Newman

Reputation: 120

Utilizing a for loop will allow you to automatically populate the list with the values you want using simple math & logic.

start = 2014
index = []
for i in range(7):
   index.append(start+i) 

This makes the code more readable, and also nearly infinitely scalable. You will also not have to populate your list manually.

Edit: As others have added, you can use Pythonic List Comprehension as well. This means you can populate a list in one line like so:

start = 2014
index = [start+i for i in range(7)] # from i=0 to i=6 (7 total elements)

Upvotes: 0

Simon
Simon

Reputation: 421

First, write it like this, easier to read and reorgranize later

start=2014
df = pd.DataFrame(
    {
        'age':past_cars_sold,
        }, 
    index = [
        start, 
        start+1,
        start+2,
        start+3,
        start+4,
        start+5,
        start+6
        ]
    )

Then, see if you can simplify it, for example

past_cars_sold = [1,2,3,4,5,6]          # dummy test values
start = 2014                            # avoid hard-coding value
years = 6                               # or group these values together
idxls = range(start, start + years, 1)  # form a list with  functions

replace it

df = pd.DataFrame(
    {
        'age':past_cars_sold,
        }, 
    index = idxls
    )

maybe also a good idea to read the official "Pythonic" way to format your code.

Upvotes: 0

Related Questions