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