如何将数据框中的值添加到字典中的另一个数据框中?

时间:2018-04-03 11:11:17

标签: python pandas dictionary dataframe

我有以下dictionarydataframe

cust_dict = {'ABC': Empty DataFrame
Columns: [Date, Particulars, Vch No., Outwards, Amount]
Index: [], 'BCD': Empty DataFrame
Columns: [Date, Particulars, Vch No., Outwards, Amount]
Index: []}

df
               Date                          Particulars       Vch Type

0   2017-04-01 00:00:00                      ABC                   Sales  
1   2017-04-06 00:00:00                      BCD                   Sales   
1   2017-04-05 00:00:00                      ABC                   Sales 

我正试图从'ABC'获取df作为key并从dataframe提取dictionary并将日期添加到Date dictionary嵌套dataframe中的{1}}列。我尝试过.atappendassign

for index, row in df.iterrows():
    print(row['Particulars'])
    cust_name = row['Particulars']
    cust_dict[cust_name] = cust_dict[cust_name]['Date'].append(date)
    cust_dict[cust_name].at['Date'] = row['Date']
    # A lot of variations of .at
    if cust_name == 'ABC':
       code = 4
       cust_dict[cust_name]['Particulars'] = code
    elif cust_name == 'BCD:
       code = 5
       cust_dict[cust_name]['Particulars'] = code

我不确定如何解决这个问题,或者这根本不可能?

df会有多行,而particulars列会让公司说ABC 4-5次或更多。

预期产出:

cust_dict['ABC']
   Date                          Particulars                  Vch Type

0   2017-04-01 00:00:00                 4                       Sales 
1   2017-04-05 00:00:00                 4                       Sales 

TIA

1 个答案:

答案 0 :(得分:1)

这是通过字典理解的一种方式。

如下所示,我建议您使用字典来映射详细信息而不是if / elif结构。

import pandas as pd

df = pd.DataFrame([['2017-04-01 00:00:00', 'ABC', 'Sales'],
                   ['2017-04-06 00:00:00', 'BCD', 'Sales'],
                   ['2017-04-05 00:00:00', 'ABC', 'Sales']],
                  index=[0, 1, 1],
                  columns=['Date', 'Particulars', 'Vch Type'])

part_map = {'ABC': 4, 'BCD': 5}

result = {k: df[df['Particulars'] == k].assign(Particulars=part_map[k]) \
             for k in df['Particulars'].unique()}

print(result['ABC'])

#                   Date  Particulars Vch Type
# 0  2017-04-01 00:00:00            4    Sales
# 1  2017-04-05 00:00:00            4    Sales