python3 之 循环(for循环,list 简化,iterrows, enumerate )

1、 For 循环基本用法

将所有的数据输出:

res=[]

res=pd.DataFrame() 【如果是矩阵】

for i in ... #循环处理文档的每一行

.........

line=..... #line为每一行的处理结果

res.append(line) #如果前面加上res=可能会报错

print(res) #res就是所需要的结果

For 循环的参数: for i in range( len(X)):

range:(start, stop[, step]) 算前不算后

range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(1, 11)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

range(0, 30, 5)

[0, 5, 10, 15, 20, 25]

size:len(X)

输出行数:x.shape[0]

输出列数:x.shape[1]

将dataframe拼接:

result = []

for t in dates:

result.append(func(t))

print (pd.concat(result, axis=1))

将list中多个dataframe拼接成dataframe,先append,再concat

for t in dates:

  expseason2.append(expseason1)

expseaso3=pd.concat(expseason2,axis=0)

2. 反向循环

for t in reversed(range(col - 1)):

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

3. iterrows 循环 :行循环

创造样例数据

import pandas as pd

import numpy as np

df = pd.DataFrame(np.random.randn(2,2), columns = list('AB'))

for x, y in df.iterrows():

print(x)

print(y)

y['A']

4. enumerate 循环: 行列名称

for x, y in df. enumerate():

print(x)

print(y)

5. list中简化for 循环:

重复

date = [1,2,3]

[x for x in date for i in range(3)]

累加+for简化:

n=index_price.shape[0]

count=[0 for x in range(0,n)]

6. 通过 dict 制造key,搜索双标签对应的值

index_htable={}

for _,row in idc.iterrows(): #按行循环

key = str(row[u'股票代码']) + '|' +str(row[u'日期']) #根据不同 的索引重新制作键值

value = str(row[u'指数代码'])

if value == '000300.SH':

value = '沪深300'

else:

value = '其他'

index_htable[key] = value # 对值重新定义索引和名称

def find_index_constitutes(code):

key = str(code[0]) + '|' + str(code[1])

if key in index_htable: # 搜寻键对应的值

print('found key',key,index_htable[key])

return index_htable[key]

else:

return '其他'

``` import pandas as pd import matplotlib.pyplot as plt # 读取数据 df = pd.read_excel(r"C:\Users\tengh\Desktop\2\农排灌溉、煤改电\煤改电\一般台区(200户以上)类型台区晋中市21年12月29日-22年01月05日96点数据鼓楼变采集点\煤改电用户功率.xlsx") # 筛选同一电表资产号(示例使用程玉林的电表号) meter_id = "1430001190021080855772" filtered_df = df[df["电表资产号"] == meter_id].copy() # 提取时间列(0:15 到 24:00) time_columns = filtered_df.columns[8:-1] # 假设时间列从第9列开始到倒数第二列 data = filtered_df[time_columns] # 转换日期格式并合并日期和时间 filtered_df["数据日期"] = pd.to_datetime(filtered_df["数据日期"]) dates = filtered_df["数据日期"].dt.strftime("%Y-%m-%d") # 绘制每日功率曲线 plt.figure(figsize=(15, 7)) for idx, row in data.iterrows(): plt.plot(time_columns, row, marker="o", label=dates.iloc[idx]) plt.title(f"电表资产号 {meter_id} 的功率时间序列(按日期)") plt.xlabel("时间") plt.ylabel("总有功功率(kW)") plt.xticks(rotation=45) plt.legend(title="日期") plt.grid(True) plt.tight_layout() plt.show()```C:\Users\tengh\AppData\Local\Programs\Python\Python313\python.exe C:\Users\tengh\Desktop\2\31.py Traceback (most recent call last): File "C:\Users\tengh\Desktop\2\31.py", line 22, in <module> plt.plot(time_columns, row, marker="o", label=dates.iloc[idx]) ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tengh\AppData\Local\Programs\Python\Python313\Lib\site-packages\matplotlib\pyplot.py", line 3827, in plot return gca().plot( ~~~~~~~~~~^ *args, ^^^^^^ ...<3 lines>... **kwargs, ^^^^^^^^^ ) ^ File "C:\Users\tengh\AppData\Local\Programs\Python\Python313\Lib\site-packages\matplotlib\axes\_axes.py", line 1777, in plot lines = [*self._get_lines(self, *args, data=data, **kwargs)] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tengh\AppData\Local\Programs\Python\Python313\Lib\site-packages\matplotlib\axes\_base.py", line 297, in __call__ yield from self._plot_args( ~~~~~~~~~~~~~~~^ axes, this, kwargs, ambiguous_fmt_datakey=ambiguous_fmt_datakey, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return_kwargs=return_kwargs ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) ^ File "C:\Users\tengh\AppData\Local\Programs\Python\Python313\Lib\site-packages\matplotlib\axes\_base.py", line 491, in _plot_args axes.yaxis.update_units(y) ~~~~~~~~~~~~~~~~~~~~~~~^^^ File "C:\Users\tengh\AppData\Local\Programs\Python\Python313\Lib\site-packages\matplotlib\axis.py", line 1754, in update_units default = self._converter.default_units(data, self) File "C:\Users\tengh\AppData\Local\Programs\Python\Python313\Lib\site-packages\matplotlib\category.py", line 106, in default_units axis.set_units(UnitData(data)) ~~~~~~~~^^^^^^ File "C:\Users\tengh\AppData\Local\Programs\Python\Python313\Lib\site-packages\matplotlib\category.py", line 182, in __init__ self.update(data) ~~~~~~~~~~~^^^^^^ File "C:\Users\tengh\AppData\Local\Programs\Python\Python313\Lib\site-packages\matplotlib\category.py", line 217, in update _api.check_isinstance((str, bytes), value=val) ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\tengh\AppData\Local\Programs\Python\Python313\Lib\site-packages\matplotlib\_api\__init__.py", line 92, in check_isinstance raise TypeError( ...<4 lines>... type_name(type(v)))) TypeError: &#39;value&#39; must be an instance of str or bytes, not a float 进程已结束,退出代码为 1
03-08
从错误信息来看,问题出现在 `matplotlib` 尝试将非字符串类型的值作为类别型数据处理。这通常是由于传递给绘图函数的数据类型不符合预期引起的。 ### 错误分析: 你在绘制图形时使用了如下的代码片段: ```python for idx, row in data.iterrows(): plt.plot(time_columns, row, marker="o", label=dates.iloc[idx]) ``` 这里的 `row` 是一个 Pandas Series 对象,包含了每一行的时间列对应的功率值(数值)。而 `label` 参数应该是字符串类型,但它接收到的是 `dates.iloc[idx]` 的结果,并且似乎在某些情况下不是字符串导致出错。 此外,`time_columns` 应该是表示时间的标签列表,但它们也可能是数字索引而不是实际的时间字符串,这也可能导致图表显示不正确。 ### 解决方案建议: 1. **检查并转换日期格式**:确保 `dates.iloc[idx]` 返回的是字符串形式。 2. **确认 x 轴刻度是否合理**:确保 `time_columns` 包含合理的小时标记(例如:"00:00","00:15"...直到"24:00")3. **调整迭代方式**:可以考虑直接用 DataFrame 的 index 和 values 来简化循环结构。 以下是修正后的代码版本: ```python import pandas as pd import matplotlib.pyplot as plt # 读取数据 df = pd.read_excel(r"C:\Users\tengh\Desktop\2\农排灌溉、煤改电\煤改电\一般台区(200户以上)类型台区晋中市21年12月29日-22年01月05日96点数据鼓楼变采集点\煤改电用户功率.xlsx") # 筛选同一电表资产号(示例使用程玉林的电表号) meter_id = "1430001190021080855772" filtered_df = df[df["电表资产号"] == meter_id].copy() # 提取时间列(假设时间列从第9列开始到倒数第二列) time_columns = list(filtered_df.columns[8:-1]) data = filtered_df[time_columns] # 转换日期格式并合并日期和时间 filtered_df["数据日期"] = pd.to_datetime(filtered_df["数据日期"]) dates_str = [date.strftime(&#39;%Y-%m-%d&#39;) for date in filtered_df["数据日期"]] # 创建 X 轴坐标轴标签 (每 15 分钟一次记录) x_ticks = time_columns.tolist() if isinstance(time_columns, pd.Index) else time_columns # 绘制每日功率曲线 plt.figure(figsize=(15, 7)) for i, date_str in enumerate(dates_str): daily_power_values = data.iloc[i] # 如果需要更友好的X轴展示,可以用range生成简单的整数序列做为替代 plt.plot(range(len(x_ticks)), daily_power_values.values.flatten(), marker=&#39;o&#39;, linestyle=&#39;-&#39;, markersize=4, linewidth=1, alpha=0.7, label=date_str) plt.title(f"电表资产号 {meter_id} 的功率时间序列(按日期)") plt.xlabel("时间段 (每个点代表一天中的某时刻)") plt.ylabel("总有功功率(kW)") # 使用自定义的xticks设置X轴标签,避免默认过密的问题 plt.xticks(ticks=[i*4 for i in range(25)], labels=["{}:{:02}".format(i//4 * 3 + 0, i%4*15) for i in range(25)]) plt.legend(title="日期") plt.grid(True) plt.tight_layout() plt.show() ``` 在这个改进版里我们做了几处改动: - 强制转成日期字符串用于 legend 标签; - 更换了对于x坐标的遍历方法,以防止原始数据index异常引起的问题; - 改进了 X 轴上时间间隔标识的方式; 通过上述修改应该能够解决你遇到的问题,同时让图像更加清晰易懂。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值