Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a value in dataframe matrix from another dataframe?

I am working on a dataset. I have one dataset which has three column company SIC code, the second column is also a company SIC code , and third column is their relationship score between two SIC code.

first dataframe

SIC SIC.1 value

10    10    0

10    12    15

10    15    17.9

and second data frame is empty data frame with SIC code in index and column

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   10  12   13

10
12
13

so I have to write a value in this second dataframe using value column from first dataframe ?

code is

for k in df20.index:
    for i in df21.index:
        for j in df21.columns:
            a = int(i)
            b = int(j)
            if df20["SIC"][k] == a & df20["SIC.1"][k] == b:
                m = df20["value"][k]
                df21[i][j] = m
            else:
                continue

please look into it, I don’t know where I am making the mistake.

>Solution :

import pandas as pd

df20 = pd.DataFrame([
    [10, 10, 0],
    [10, 12, 15],
    [10, 15, 17.9],
], columns=['SIC', 'SIC.1', 'value'])

df21 = pd.DataFrame(
    index=[10, 12, 13], columns=[10, 12, 13]
)

for i, row in df20.iterrows():
    for SIC in df21.index:
        for SIC1 in df21.columns:
            if row['SIC'] == SIC and row['SIC.1'] == SIC1:
                df21.loc[SIC, SIC1] = row['value']
print(df21)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading