简体   繁体   English

使用python迭代并填充excel中的列的正确方法

[英]Correct way to iterate through and populate a column in excel with python

Okay I need some help.好的,我需要一些帮助。 This was supposed to iterate through the 35,021 rows of an excel spreadsheet and populate the column drg_id from the DRG.xlsx into a cvs sheet .这应该遍历 excel 电子表格的 35,021 行,并将 DRG.xlsx 中的 drg_id 列填充到 cvs 表中。 Instead it only populated just the original 7 items into 7 of the 35,021 rows in a new column.相反,它仅将原始 7 项填充到新列中 35,021 行中的 7 行中。 What am I doing wrong?我究竟做错了什么?

drg = pd.read_excel('C:/Cardiac DRG.xlsx', sheet_name=0, index_col=0)
list_A = drg['DRG'].tolist()
print(list_A)
series_A = pd.Series(list_A)
##Add in  the DRG to the next empty column
##df['DRG'] = series_A.values
drg_list = []
drgs = list_A 
##series_A #unique names in user_id column
drg_id_col = list(drg['DRG']) #assign column to list
def rand_reviewer(list_of_drgs):#function to generate rand user
    return list_of_drgs[random.randint(0,35021)]
for i in range(35021, len(drgs)): #iterate over list 
    drg_list.append(rand_reviewer(drgs))
    while drg_id_col[i] == drg_list[i]: #generate random user until id's don't match
        drg_list[i] = rand_reviewer(drgs)
series_B = pd.Series(drg_id_col)
df3['drg_id'] = series_B  ##add new column to df

This extracts the DRG column from drg , and populates a new column in df3 with random selections from that column.这会从drg中提取 DRG 列,并使用来自该列的随机选择填充df3中的新列。 That seems to be what your code was trying to do.这似乎是你的代码试图做的。

drg = pd.read_excel('C:/Cardiac DRG.xlsx', sheet_name=0, index_col=0)
list_A = drg['DRG'].tolist()
df3['drg_id'] = random.choices(list_A, k=len(df3.index))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM