我试图优化代码时,为了获得一个表与数据读取CSV文件的Pandas 工作.
这段代码运行正常,但相当麻烦:
pd_table = pd.DataFrame(
个个
{
10: [sheet['B' + str(item)].value for item in range(1,29) if sheet['A' + str(item)].value == 10],
20: [sheet['B' + str(item)].value for item in range(1,29) if sheet['A' + str(item)].value == 20],
30: [sheet['B' + str(item)].value for item in range(1,29) if sheet['A' + str(item)].value == 30],
40: [sheet['B' + str(item)].value for item in range(1,29) if sheet['A' + str(item)].value == 40],
50: [sheet['B' + str(item)].value for item in range(1,29) if sheet['A' + str(item)].value == 50],
60: [sheet['B' + str(item)].value for item in range(1,29) if sheet['A' + str(item)].value == 60],
70: [sheet['B' + str(item)].value for item in range(1,29) if sheet['A' + str(item)].value == 70]
}
结果是一个包含数据的表
我将此代码简化为以下代码:
values= [10, 20, 30, 40, 50, 60, 70]
个
pd_table = pd.DataFrame(
个个
dict(zip(values, [[sheet['B' + str(item)].value for item in range(6,29) if sheet['A' + str(item)].value == 10]]*len(values))), index = ['10.08', '20.08', '30.08']
个
)
个
你能告诉我如何更换建筑中的10号吗?
...sheet['A' + str(item)].value == 10...
个
使用"N",它将迭代列表"Values"中序列10、20...70中的数字?
如果我使用sheet['A' + str(item)].value == i for i in values
,则会得到一个错误:
local variable 'i' referenced before assignment