我想遍历DataFrame的各行,并为新的DataFrame赋值。我像这样间接地完成了这项任务:
#first I read the data from df1 and assign it to df2 if something happens
counter = 0                         #line1
for index,row in df1.iterrows():    #line2
    value = row['df1_col']          #line3
    value2 = row['df1_col2']          #line4
    #try unzipping a file (pseudo code)                  
        df2.loc[counter,'df2_col'] = value  #line5
        counter += 1                        #line6
    #except
        print("Error, could not unzip {}")  #line7
#then I set the desired index for df2
df2 = df2.set_index(['df2_col'])  #line7有没有办法直接在line5中将这些值赋给df2的索引?对不起,我原来的问题不清楚。我正在根据发生的事情创建一个索引。
发布于 2016-07-22 01:19:58
有很多方法可以做到这一点。根据您的代码,您所做的一切只是创建了一个带有来自df1.df1_col的值的索引的空df2数据帧。您可以直接这样做:
df2 = pd.DataFrame([], df1.df1_col)
#                   ^     ^
#                   |     |
# specifies no data, yet  |
#                        defines the index如果您担心必须过滤df1,那么您可以这样做:
# cond is some boolean mask representing a condition to filter on.
# I'll make one up for you.
cond = df1.df1_col > 10
df2 = pd.DataFrame([], df1.loc[cond, 'df1_col'])发布于 2016-07-22 00:58:07
不需要迭代,你可以这样做:
df2.index = df1['df1_col']如果您确实想要迭代,请将其保存到列表并设置索引。
https://stackoverflow.com/questions/38510059
复制相似问题