我正在尝试在使用 Pandas 时优化代码,以获得包含从 csv 文件读取的数据的表格。
这段代码可以正确运行,但是相当麻烦:
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”,这将从列表“值”中迭代序列 10, 20...70 中的数字?
如果我使用
sheet['A' + str(item)].value == i for i in values
,则会出现错误:
local variable 'i' referenced before assignment
你不能使用字典理解吗?
pd_table = pd.DataFrame(
{val: [[sheet['B' + str(item)].value for item in range(6,29)
if sheet['A' + str(item)].value == val]]*len(values)))
for val in values},
index = ['10.08', '20.08', '30.08']
)