我能夠列印小資料框并看到它正在正確生成,我已經使用下面的代碼撰寫了它。然而,我的最終結果只包含最終合并的結果,而不是傳遞每個結果并合并它們。
MIK_Quantiles 是第一個較大的資料幀,df2_t 是在 while 回圈中生成的較小的資料幀。資料幀都正確生成并且合并有效,但我只剩下最后一次合并的結果。我希望它將當前 df2_t 與前一個回圈的已合并結果 (df_merged) 合并。我希望這是有道理的!
i = 0
while i < df_length - 1:
cur_bound = MIK_Quantiles['bound'].iloc[i]
cur_percentile = MIK_Quantiles['percentile'].iloc[i]
cur_bin_low = MIK_Quantiles['auppm'].iloc[i]
cur_bin_high = MIK_Quantiles['auppm'].iloc[i 1]
### Grades/Counts within bin, along with min and max
df2 = df_orig['auppm'].loc[(df_orig['bound'] == cur_bound) & (df_orig['auppm'] >= cur_bin_low) & (df_orig['auppm'] < cur_bin_high)].describe()
### Add fields of interest to the output of describe for later merging together
df2['bound'] = cur_bound
df2['percentile'] = cur_percentile
df2['bin_name'] = 'bin name'
df2['bin_lower'] = cur_bin_low
df2['bin_upper'] = cur_bin_high
df2['temp_merger'] = str(int(df2['bound'])) '_' str(df2['percentile'])
# Write results of describe to a CSV file and transpose columns to rows
df2.to_csv('df2.csv')
df2_t = pd.read_csv('df2.csv').T
df2_t.columns = ['count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max', 'bound', 'percentile', 'bin_name', 'bin_lower', 'bin_upper', 'temp_merger']
# Merge the results of the describe on the selected data with the table of quantile values to produce a final output
df_merged = MIK_Quantiles.merge(df2_t, how = 'inner', on = ['temp_merger'])
pd.merge(df_merged, df2_t)
print(df_merged)
i = i 1
uj5u.com熱心網友回復:
除了 increment 之外,您的回圈沒有做任何有意義的事情i。
您合并了 2 個(靜態)dfs(MIK_Quantiles和df2_t),并且執行了該df_length次數。每次執行此操作(回圈的第一次、第 i 次和最后一次迭代)時,都會覆寫輸出變數df_merged。
要保留在前一個回圈迭代中創建的任何輸出,您需要連接所有創建的df2_t:
df2 = pd.concat([df2, df2_t])在回圈的每次迭代期間將新創建的資料“附加”df2_t到輸出資料幀df2,因此最終所有資料都將包含在df2
然后,在回圈之后,merge那個到MIK_Quantiles
pd.merge(MIK_Quantiles, df2)(不是df2_t(!))合并上一個輸出
df2 = pd.DataFrame([]) # initialize your output
for i in range(0, df_length):
df2_t = ... # read your .csv files
df2 = pd.concat([df2, df2_t])
df2 = ... # do vector operations on df2 (process all of the df2_t at once)
out = pd.merge(MIK_Quantiles, df2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/424443.html
上一篇:在python腳本中集成一個回圈
