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

Append values of for loop to dataframe

The below code works and prints value, but I need the value to be appended to data frame with column ‘NAME’ and ‘SystemName’ on loop.

def name():
  for i in conn.Win32_LogicalDisk():
    if i.NAME is not None:
       print(i.NAME)
       print(i.SystemName)

I tried different ways such as print output capture, setvalue, creating varaible. I couldn’t.

df['NAME'].set_value = i.NAME
df['Systemname'].set_value = i.SystemName

Output

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

| NAME | SystemName |
|------|------------|
| C:   | aaaaa      |
| D:   | bbbbb      |

>Solution :

You could use pd.concat. You would need to create a DataFrame in each iteration of the loop and then concatenate it to the other original DataFrame.
In your case:

def name():
    # Create Empty DataFrame
    df = pd.DataFrame(columns = ['NAME', 'Systemname'])
    for i in conn.Win32_LogicalDisk():
        if i.NAME is not None:
            new_df = pd.DataFrame(data = [[i.Name, i.SystemName]], columns = ['NAME', 'Systemname'])
            df= pd.concat([df, new_df])

If you prefer one-liner:

def name():
    # Create Empty DataFrame
    df = pd.DataFrame(columns = ['NAME', 'Systemname'])
    for i in conn.Win32_LogicalDisk():
        if i.NAME is not None:
            df = pd.concat([df, pd.DataFrame(data = [[i.Name, i.SystemName]], columns = ['NAME', 'Systemname'])])
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