Pandas:更改对象的值

huangapple go评论63阅读模式
英文:

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(&#39;Meandq.csv&#39;, 
                      sep=&#39;;&#39;)
year= &#39;2022&#39;
qy= dailyq.loc[(dailyq[&#39;Date&#39;] &gt;= &#39;01/01/&#39; + year) &amp; 
                (dailyq[&#39;Date&#39;] &lt;= &#39;31/12/&#39; + 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(&#39;Meandq.csv&#39;, sep=&#39;;&#39;)

for year in range(1950, 2023):
	qy= dailyq.loc[(dailyq[&#39;Date&#39;] &gt;= &#39;01/01/&#39;+str(year)) &amp; (dailyq[&#39;Date&#39;] &lt;= &#39;31/12/&#39;+str(year))]

huangapple
  • 本文由 发表于 2023年7月3日 15:01:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602512.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定