Search code examples
pythonpandasdataframewmic

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

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

Solution

  • You could build the dataframe directly, without any appending etc.:

    def name():
        return pd.DataFrame(
            ([i.Name, i.SystemName] for i in conn.Win32_LogicalDisk()
             if i.Name is not None),
            columns=['NAME', 'SystemName']
        )
    

    If you need to do additional tasks with the dataframe in the function:

    def name():
        df = pd.DataFrame(
            ([i.Name, i.SystemName] for i in conn.Win32_LogicalDisk()
             if i.Name is not None),
            columns=['NAME', 'SystemName']
        )
        #  ... do the tasks ... 
        return df