读入数据并将其设置为带有Pandas的DataFrame的索引

时间:2016-07-21 16:50:50

标签: python pandas dataframe

我想遍历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

有没有办法直接在第5行中将值分配给df2的索引?对不起我的原始问题不清楚。我正在根据发生的事情创建一个索引。

2 个答案:

答案 0 :(得分:3)

有很多方法可以做到这一点。根据您的代码,您所做的就是创建一个空的df2数据框,其索引值为df1.df1_col。你可以直接这样做:

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'])

答案 1 :(得分:0)

无需迭代,您可以这样做:

df2.index = df1['df1_col']

如果您真的想要迭代,请将其保存到列表并设置索引。