簡體   English   中英

通過使用read_csv()從多個文件中讀取數據來創建多級DataFrame [已解決]

[英]Create Multilevel DataFrame by reading in data from multiple files using read_csv() [SOLVED]

我有10個文件,它們的格式和列名都相同(不同文件中的值不同):

    event_code  timestamp   counter
0   9071        1165783     NaN
1   9070        1165883     NaN
2   8071        1166167     NaN
3   7529        NaN         0.0
4   8529        NaN         1.0
5   9529        NaN         1.0

由於文件的性質,我試圖將這些數據存儲在多級數據box_num ,如下所示:(最終,我希望box_num級別box_num上升到10)

box_num                1                                 2                ...   
col_names   event_code  timestamp   counter |event_code timestamp   counter
      0     9071          1270451     1     |   8529       NaN       1    ...
      1     9070          1270484     0     |   9529       NaN       0    ...
      2     9071          1270736     1     |   5520       3599167   2    ...
      3     9070          1272337     3     |   7171       3599169   1    ...

最初我以為我可以使用鍵作為層次結構索引,將數據框作為歸類數據框,從而用字典創建多級數據框

col_names = ['event_code','timestamp', 'counter']

df_dict = {}
for i in range(len(files)):
    f = files[i]  # actual file name

    df = pd.read_csv(f, sep=":", header=None, names=col_names)
    df_dict[i+1] = df   # 'i+1' so that dict_key can correspond to actual box number 

但是我很快意識到我無法從字典創建多級索引或數據框。 所以要創建一個多級索引,這就是我所做的,但是現在我被困在下一步要做的事情上...

(box_num, col_list) = df_dict.keys(), list(df_dict.values())[0].columns

如果還有其他更有效,簡潔的方法來解決此問題,請也告訴我。 理想情況下,我想在for循環之后立即創建多級數據框

::更新:: [已解決]

因此,我最終想出了一種使用pd.concat()從for循環創建多級數據幀的方法。 我將在下面發布我的答案。 希望它對某人有幫助。

col_names = ['event_code', 'timestamp', 'counter']

result = []
box_num = []

for i in range(len(files)):
    f = files[i]
    box_num.append(i+1)  # box_number 

    df = pd.read_csv(f, sep=":", header=None, names=col_names)
    result.append(df)

# # pd.concat() combines all the Series in the 'result' list
# # 'Keys' option adds a hierarchical index at the outermost level of the data.

final_df = pd.concat(result, axis=1, keys=box_num, names=['Box Number','Columns'])


我認為您應該為此任務使用數據透視表或pandas groupby函數。 兩者都不能完全滿足您上面的要求,但是使用起來會更簡單。

以您的代碼為起點:

col_names = ['event_code','timestamp', 'counter']
data = pd.DataFrame()

for i in range(len(files)):
    f = files[i]
    df = pd.read_csv(f, sep=":", header=None, names=col_names)
    # instead of a dictionary try creating a master DataFrame
    df['box_num'] = i
    data = pd.concat([data, df]).reset_index(drop=True)
    data['idx'] = data.index
# option 1 create a pivot table 
pivot = data.pivot(index='idx', columns='box_num', values=col_names)

# option 2 use pandas groupby function
group = data.groupby(['idx', 'box_num']).mean()

希望其中之一可以幫助您朝正確的方向前進或為您要實現的目標而努力。 祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM