我有以下dictionary
和dataframe
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}}列。我尝试过.at
,append
,assign
。
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
答案 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