2

Let's say I have 2 pivot tables: dfp1 and dfp2.

My current code is:

if not dfp2.empty:
 for key in dfp1['col1'].keys():
  if key not in dfp2['col2'].keys():
   dfp2['col2'][key] = 0

The purpose is to check if a value exist in col1 of dfp1 exists in col2 of dfp2. If not, make it 0.

However this does not add the value to dfp2['col2']. How should I go to add this 0 value?

Thanks in advance.

Edit:

Some sample data:

dfp1['col1']

*Currency Code
CNH         0.00
INR         0.00
JPY   -985718.00
SGD       -70.69
USD      9103.94

dfp2['col2']

JPY    8030442.00
MYR     153050.00
SGD     636836.44
USD     553863.09

Expected output for dfp2['col2']:

JPY    8030442.00
MYR     153050.00
SGD     636836.44
USD     553863.09
CNH     0.00
INR     0.00
3
  • have you tried pd.merge() then use df.fillna(0)? It would be helpful if you show a sample of your data Commented Aug 10, 2021 at 3:26
  • Can you share sample data and expected output, to help you better. Commented Aug 10, 2021 at 3:48
  • I've added the sample data to the post. Commented Aug 10, 2021 at 4:07

1 Answer 1

1

Solution with Series.align

We can align the two columns along the index axis

col2 = dfp2['col2'].align(dfp1['col1'], fill_value=0)[0]

Solution with Series.reindex

col2 = dfp2['col2'].reindex(dfp2.index.union(dfp1.index), fill_value=0)

print(col2)

CNH          0.00
INR          0.00
JPY    8030442.00
MYR     153050.00
SGD     636836.44
USD     553863.09
Name: col2, dtype: float64
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.