[英]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.
现在我一次只做一个,只是想知道是否有更简单的方法来重写它。
Karl's comment seems the most straightforward. 卡尔的评论似乎是最直接的。 No list needed -- just give pandas a
range
object:不需要列表——只需给 pandas 一个
range
object:
start = 2014
df = pd.DataFrame({'age': past_cars_sold}, index=range(start, start+7))
Utilizing a for loop will allow you to automatically populate the list with the values you want using simple math & logic.利用 for 循环将允许您使用简单的数学和逻辑自动使用所需的值填充列表。
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 usePythonic List Comprehension as well.编辑:正如其他人添加的那样,您也可以使用Pythonic List Comprehension 。 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)
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.阅读格式化代码的官方“Pythonic”方式也许也是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.