[英]Read in data and set it to the index of a DataFrame with Pandas
我想遍歷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'])
無需迭代,您可以執行以下操作:
df2.index = df1['df1_col']
如果您確實要迭代,請將其保存到列表中並設置索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.