在for循环中在字典中添加数据框行?

时间:2019-06-10 13:27:43

标签: python dataframe dictionary

我有如下字典:

    m_dict={'month1':None,'month2':None, 'month3':None }

我有一个如下数据框:

    m_frame1:

    Id, f1, f2, f3, …, fn 
    X1, 34,5,5,…, 23
    X1, 30,15,2,…, 53
    X1, 33,10,2,…, 13

    m_frame2:

    Id, f1, f2, f3, …, fn 
    X2, 21,6,8,…, 12
    X2, 37,19,0,…, 45
    X2, 32,11,2,…, 24

    m_frame3:

    Id, f1, f2, f3, …, fn 
    X3, 41,16,28,…, 2
    X3, 17,11,21,…, 5
    X3, 19,17,87,…, 4

我想在循环中的每个特定键中添加行(来自三个数据帧)。所以我想要的字典应该像这样:例如,在:

    m_dict[‘month1’]: 

    Id, f1, f2, f3, …, fn 
    X1, 34,  5,  5, …, 23
    X2, 21,  6,  8, …, 12
    X3, 41,  16, 28,…,  2

    m_dict[‘month2’]: 

    Id, f1, f2, f3, …, fn
    X1, 30, 15, 2,  …, 53
    X2, 37, 19, 0,  …, 45
    X3, 17, 11, 21, …, 5

以此类推。有解决问题的主意吗?

2 个答案:

答案 0 :(得分:0)

该技术concat怎么样,然后使用内置方法dict转换为to_dict()

import pandas as pd
import io
from pprint import pprint

# Generating an example
zz = """Id f1 f2 f3
    X3 41 16 28
    X3 17 11 21
    X3 19 17 87"""

df1 = pd.read_table(io.StringIO(zz), delim_whitespace=True)
df2 = pd.read_table(io.StringIO(zz), delim_whitespace=True)

# getting all dataframes in a list
all_dfs = [df1, df2]

m_dict={'month1':None,'month2':None, 'month3':None }

# Concat all the dataframe and creating the association between months and df
result = pd.concat(all_dfs, keys=['month1', 'month2'], ignore_index=False)
# Wrangling used to remove the unnecessary index
result = result.reset_index(level=1).drop(columns=['level_1'])
# Converting to the expected dict
result.to_dict('index')


# {'month1': {'Id': '    X3', ' f1': 19, ' f2': 17, ' f3': 87},
# 'month2': {'Id': '    X3', ' f1': 19, ' f2': 17, ' f3': 87}}

答案 1 :(得分:0)

一种非常简单粗略的方法是:

首先让我们创建示例数据帧:

m_frame1=pd.DataFrame({'Id':['X1','X1','X1'], 'f1':[34,30,33], 'f2':[5,15,10], 'f3':[23,53,13]}) 
m_frame2=pd.DataFrame({'Id':['X2','X2','X2'], 'f1':[21,37,32], 'f2':[6,19,0], 'f3':[12,45,24]}) 
m_frame3=pd.DataFrame({'Id':['X3','X3','X3'], 'f1':[41,17,19], 'f2':[16,11,17], 'f3':[2,5,4]}) 


print(m_frame1)

   Id  f1  f2  f3
0  X1  34   5  23
1  X1  30  15  53
2  X1  33  10  13


print(m_frame2)

   Id  f1  f2  f3
0  X2  21   6  12
1  X2  37  19  45
2  X2  32   0  24


print(m_frame3)

   Id  f1  f2  f3
0  X3  41  16   2
1  X3  17  11   5
2  X3  19  17   4

现在:

k=[]
for a in range(len(m_frame1)):
    k.append(m_frame1.iloc[a].values)
    k.append(m_frame2.iloc[a].values)   
    k.append(m_frame3.iloc[a].values)   
    m_dict[f'month{a+1}']=pd.DataFrame(k)
    k=[]

中提琴,您得到:

print(m_dict['month1'])

    0   1   2   3
0  X1  34   5  23
1  X2  21   6  12
2  X3  41  16   2