英文:
Pandas: change object's value
问题
Python新手在寻找解决方案时遇到问题。
我的数据非常简单:日期列(包含很多年份)和流量列。我想要绘制年度时间与流量的图表,所以我创建了一个对象,其中包含我想要绘制的年份,然后使用一行代码来过滤原始数据中所需的年份。
dailyq = pd.read_csv('Meandq.csv', sep=';')
year = '2022'
qy = dailyq.loc[(dailyq['Date'] >= '01/01/' + year) &
(dailyq['Date'] <= '31/12/' + year)]
使用这种方法,我必须手动更改年份的值,但是当我需要处理长时间序列时(例如从1950年到2022年),我会感到很笨拙,因此我想使用循环来自动更改年份。有什么想法吗?
我尝试了一些循环,但我真的找不到让Python理解我的逻辑的方法。
非常感谢您的时间。
英文:
Python newbie here having problems to find a solution.
My data is quite simple: date column (lots of years) and flow column. Wanted to plot time vs flow yearly, so I created an object with the year I want to plot followed by a line to filter the desired year out the original data.
dailyq = pd.read_csv('Meandq.csv',
sep=';')
year= '2022'
qy= dailyq.loc[(dailyq['Date'] >= '01/01/' + year) &
(dailyq['Date'] <= '31/12/' + year)]
With this method, I have to change manually the value of year, but I feel dork when I have to process long time series (i.e. from 1950 to 2022), so I wanted to use a loop to change automatically the year. Some ideas, please?
I just tried some loops but I really can't find the logic to make Python understand me.
Thank you so much for your time.
答案1
得分: 0
你可以将年份作为整数循环,并在查询时将其转换为字符串,就像这样。
dailyq = pd.read_csv('Meandq.csv', sep=';')
for year in range(1950, 2023):
qy = dailyq.loc[(dailyq['Date'] >= '01/01/' + str(year)) & (dailyq['Date'] <= '31/12/' + str(year))]
英文:
You can loop year as an integer and cast it as a string while querying, like this.
dailyq = pd.read_csv('Meandq.csv', sep=';')
for year in range(1950, 2023):
qy= dailyq.loc[(dailyq['Date'] >= '01/01/'+str(year)) & (dailyq['Date'] <= '31/12/'+str(year))]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论