0

Say I have a dict where I want to update values daily with today's values, if in the same month, else extend the list for a new month.

df_dict = pd.DataFrame({
    'orgnr': np.arange(1,6,1),
    'periode': '2022-05',
    'a':'tull',
    }).to_dict('list')

output: dict of lists

 {'orgnr': [1, 2, 3, 4, 5],
 'periode': ['2022-05', '2022-05', '2022-05', '2022-05', '2022-05'],
 'a': ['tull', 'tull', 'tull', 'tull', 'tull']}

And I extend the list if there is a new month:

df_newMonth = pd.DataFrame({
    'orgnr': np.arange(1,6,1),
    'periode': '2022-07',
    'a':'new month',
    }).to_dict('list')

for k, v in df_newMonth.items():
        df_dict[k].extend(v)

Let's say there is a new day in the new month

df_newDay = pd.DataFrame({
    'orgnr': np.arange(1,6,1),
    'periode': '2022-07',
    'a':'new day in new month',
    }).to_dict('list')

And now I want to update the recent list values for all key-values where periode is equal to, in this case, '2022-07'

I tried something like this,

df_dict.update({k: v for k, v in df_newDay.items() if '2022-07' in df_dict['periode']})
    
df_dict.update({k: v if [num for num in df_dict['periode'] if num == '2022-07'] else v for k, v in df_newDay.items()})

Expected Output:

 {'orgnr': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
 'periode': ['2022-05', '2022-05', '2022-05', '2022-05', '2022-05', '2022-07', '2022-07', '2022-07', '2022-07', '2022-07'],
 'a': ['tull', 'tull', 'tull', 'tull', 'tull', 'new day in new month', 'new day in new month', 'new day in new month', 'new day in new month', 'new day in new month' ]}

Maybe it's not the best way to store data, in that case can someone point me in another direction?

Thank you!

Jon
  • 51
  • 6
  • why do you use pandas if you convert back to dictionary? – mozway Jun 02 '22 at 12:28
  • Because I find it easier to work with a dataframe for other stuff, and according to this I should not grow a dataframe https://stackoverflow.com/questions/10715965/create-a-pandas-dataframe-by-appending-one-row-at-a-time – Jon Jun 02 '22 at 12:42
  • or for this example, I just found it faster to type it this way, no particular reason – Jon Jun 02 '22 at 12:52

0 Answers0