I'm struggling behind a python script to import a formatted CSV ("," as delimiter) as DataFrame, group the result by value in specific column and based on that groups I need to output a formatted CLI config script for a network device.
I would be very happy if someone could help me
My CSV (users.csv) is something like this
user,email,group
pippo1,pippo1@corporate.com,grp1
pippo2,pippo2@corporate.com,grp1
pippo10,pippo10@corporate.com,grp2
user10,user10@corporate.com,grp3
user93,user93@corporate.com,grp1
Now I'm able to import and group data by "group" column with
df = pd.read_csv('users.csv', sep=',') grouped = df.groupby('group')
What I'm not able to do is to produce a text output like this
Intro
edit grp1
append member pippo1 pippo2 user93
next
edit grp2
append member pippo10
next
edit grp3
append member user10
next
end
With the "for" below I get this result and unfortunately is not what I'm trying to achieve
for group in grouped: print (group) grp = group[0] usergrp_text += "edit " + grp usertoappend = group[1] print (usertoappend['user'].to_string(index=False))
print of group variable
('grp1', user email group 0 pippo1 pippo1@corporate.com grp1 1 pippo2 pippoilbello@corporate.com grp1 4 user93 uservalgopoco@corporate.com grp1)
print of group[1] variable
pippo1 pippo2 user93
When doing for group in grouped
in reality you are getting a tuple with groupname,groupcontents.
Use the groupname for the edit
and expand the users with a comprehension of the user
field of the "sub-dataframe". Not the most efficient, but gets the job done
grouped = df.groupby('group')
print("Intro")
for k,g in grouped:
print(f"edit {k}")
print(f"append member {' '.join([x for x in g.user])}")
print("next")
print("end")
Prints:
Intro
edit grp1
append member pippo1 pippo2
next
edit grp2
append member pippo10
next
edit grp3
append member user10
next
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.