我想迭代 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的索引?抱歉,我原来的问题不清楚。我正在根据发生的事情创建一个索引。
最佳答案
有很多方法可以做到这一点。根据您的代码,您所做的只是创建一个空的 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'])
关于python - 使用 Pandas 读取数据并将其设置为 DataFrame 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38510059/