简体   繁体   English

Python 函数的月份范围

[英]Python Function monthrange

I have the following: I imported an excel list called example with the date in the form day-month-year, which is the index, and then I have in a second column the corresponding volumes.我有以下内容:我导入了一个名为 example 的 excel 列表,其中的日期格式为日-月-年,这是索引,然后我在第二列中有相应的卷。

With python I extracted the month and the year.使用 python 我提取了月份和年份。

example['Year']= example.index.year
example['month']= example.index.month

Now I want to get the days per month现在我想得到每个月的天数

I tried:我试过:

x=monthrange(example['Year'], example'[month'])

Does not work, the result is ambiguous.行不通,结果模棱两可。

for i in example['year']:
   for j in eaxmaple['month']:
       x=monthrange(i,j)

does not work either, since it does not combine the year and month, it just loops through all year, and then trhough all months.也不起作用,因为它没有结合年份和月份,它只是循环遍历全年,然后遍历所有月份。

How do I solve this?我该如何解决这个问题? I would like to add a colum with the days per month, so I have one colum with the date, one column with the year, one column with the month and one with the days per month我想添加一个带有每月天数的列,所以我有一列带有日期,一列带有年份,一列带有月份,一列带有每个月的天数

Does this work?这行得通吗? :

x=[monthrange(i, j) for (i, j) in zip(example['Year'], example['month'])]

Or if you want only the days in month:或者,如果您只想要一个月中的天数:

x=[monthrange(i, j)[1] for (i, j) in zip(example['Year'], example['month'])]

Or with pandas:或者用熊猫:

example['days_in_month'] = example.apply(lambda df: monthrange(df['Year'], df['month']))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM