我想遍歷一堆 .txt 檔案,對于每個處理它的檔案(洗掉列、更改名稱、nan 等)以獲得 df1 的最終資料幀輸出,它具有特定的日期、緯度、經度和變數分配給它。在回圈中,我想獲取 df_all,其中包含來自所有檔案的所有資訊(很可能按日期順序)。
但是,我的每個資料框的長度都不同,并且它們有可能在該列中共享相同的日期 緯度/經度值。
我已經撰寫了代碼來單獨輸入和處理檔案,但我一直堅持如何將它變成一個更大的回圈(通過 concat/append ...?)。
我試圖以一個大資料框(df_all)結束,其中包含不同檔案(df1 輸出)的所有“分散”資訊。此外,如果日期和緯度/經度有沖突,我會找到平均值。這可以在 python/pandas 中完成嗎?
對于任何多個問題的任何幫助都將不勝感激!或有關如何解決此問題的想法。
uj5u.com熱心網友回復:
這是由 for 回圈讀入的假表并讀入concat大表。然后在將所有行添加到單個大表后,您可以將列中具有相同值的多行組合在一起,A并mean以B和C列為例。您應該能夠自己運行這段代碼,我希望這有助于為您提供關鍵字來搜索與您類似的其他問題!
import pandas as pd
#Making fake table read ins. you'd be using pd.read_csv or similar
def fake_read_table(name):
small_df1 = pd.DataFrame({'A': {0: 5, 1: 1, 2: 3, 3: 1}, 'B': {0: 4, 1: 4, 2: 4, 3: 4}, 'C': {0: 2, 1: 1, 2: 4, 3: 1}})
small_df2 = pd.DataFrame({'A': {0: 4, 1: 5, 2: 1, 3: 4, 4: 3, 5: 2, 6: 5, 7: 1}, 'B': {0: 3, 1: 1, 2: 1, 3: 1, 4: 5, 5: 1, 6: 4, 7: 2}, 'C': {0: 4, 1: 1, 2: 5, 3: 2, 4: 4, 5: 4, 6: 5, 7: 2}})
small_df3 = pd.DataFrame({'A': {0: 2, 1: 2, 2: 4, 3: 3, 4: 1, 5: 4, 6: 5}, 'B': {0: 1, 1: 2, 2: 3, 3: 1, 4: 3, 5: 5, 6: 4}, 'C': {0: 5, 1: 2, 2: 3, 3: 3, 4: 5, 5: 4, 6: 5}})
if name == '1.txt':
return small_df1
if name == '2.txt':
return small_df2
if name == '3.txt':
return small_df3
#Start here
txt_paths = ['1.txt','2.txt','3.txt']
big_df = pd.DataFrame()
for txt_path in txt_paths:
small_df = fake_read_table(txt_path)
# .. do some processing you need to do somewhere in here ..
big_df = pd.concat((big_df,small_df))
#Taking the average B and C values for rows that have the same A value
agg_df = big_df.groupby('A').agg(
mean_B = ('B','mean'),
mean_C = ('C','mean'),
).reset_index()
print(agg_df)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452190.html
