Home > OS >  Append values of for loop to dataframe
Append values of for loop to dataframe

Time:03-27

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      |

CodePudding user response:

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

CodePudding user response:

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'])])

CodePudding user response:

Instead of trying to append to an empty dataframe for every row, you can just create arrays for each column and then create the dataframe using those columns once they are full.

names = []
systemnames = []
for i in conn.Win32_LogicalDisk():
    names.append(i.NAME)
    systemnames.append(i.SystemName)
    
df = pd.DataFrame(list(zip(names, systemnames)),columns=['NAME', 'SystemName'])
  • Related