簡體   English   中英

有沒有一種方法可以從帶有值列表的字典中創建數據框?

[英]Is there a way to create a dataframe from a dictionary with list of values?

我有一個字典myDict ,我想使用此myDict創建一個數據框df ,如下所示:

myDict = {
1: [''],
2: ['07/19/2017', ' 10/18/2007', '12/20/2002','12/20/2002' ],
3: ['07/19/2017', ' 10/18/2007'],
4: ['12/13/1993'],
5: [''],
6: ['08/01/2007'],
7: ['04/23/2007'],
8: ['02/06/2007'],
9: ['02/06/2007'],
10: ['11/08/2001'],
11: [''],
12: [''],
13: ['12/20/2002']
}

df
ID    Col1         Col2          Col3         Col4
1     
2     07/19/2017   10/18/2007    12/20/2002   12/20/2002 
3     07/19/2017   10/18/2007 
4     12/13/1993   
5     
6     08/01/2007
7     04/23/2007
8     02/06/2007
9     02/06/2007
10    11/08/2001
11    
12    
13    12/20/2002

我如何做到這一點? 謝謝。

將所有內容放到函數中都無法正常工作...

def split_Date(df):
    Dates1 = df.set_index('IDX')['Date'].to_dict()
    dates = {}
    for k, v in Dates1.items():
       v = v.split(',')
       dates[k] = [i for i in v]
    dates = {k: sorted(v, key=lambda x: datetime.strptime(x.strip(), "%m/%d/%Y") if x != "" else x) for k, v in dates.items()}
    df_dates = pd.DataFrame.from_dict(dates, orient="index").fillna('').rename_axis("IDX").rename(columns="Date{}".format).reset_index()
    df = pd.merge(df, df_dates, on='IDX', how='inner', suffixes=('_chem', '_df'))
    return df #Adding this doesn't make any difference

在函數外部運行此代碼非常有效。 但是,這要求我每次有新的data都要在所有行中更改myData的值。 這不像具有功能那樣高效

Dates1 = myData.set_index('IDX')['Date'].to_dict()
dates = {}
for k, v in Dates1.items():
    v = v.split(',')
    dates[k] = [i for i in v]
dates = {k: sorted(v, key=lambda x: datetime.strptime(x.strip(), "%m/%d/%Y") 
if x != "" else x) for k, v in dates.items()}
df_dates = pd.DataFrame.from_dict(dates, orient="index").fillna('').rename_axis("IDX").rename(columns="Date{}".format).reset_index()
myData = pd.merge(myData, df_dates, on='IDX', how='inner', suffixes=('_chem', '_df'))

您可以使用pd.DataFrame.from_dict讀取它,並通過orient參數將鍵設置為索引:

pd.DataFrame.from_dict(myDict, orient="index").fillna('')

#            0           1           2           3
#1              
#2  07/19/2017  10/18/2007  12/20/2002  12/20/2002
#3  07/19/2017  10/18/2007      
#4  12/13/1993          
#5              
#6  08/01/2007          
# ...

要將鍵設置為單獨的列,可以使用reset_index

(pd.DataFrame.from_dict(myDict, orient="index")
 .fillna('')
 .rename_axis("ID")
 .rename(columns="Col{}".format)
 .reset_index())

#  ID         Col0        Col1        Col2        Col3
#0  1               
#1  2   07/19/2017  10/18/2007  12/20/2002  12/20/2002
#2  3   07/19/2017  10/18/2007      
#3  4   12/13/1993          
#4  5
# ...               

暫無
暫無

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

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