Home > Blockchain >  Python - Import CSV as DataFrame, filter with groupby and export results as formatted text
Python - Import CSV as DataFrame, filter with groupby and export results as formatted text

Time:05-19

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,[email protected],grp1
pippo2,[email protected],grp1
pippo10,[email protected],grp2
user10,[email protected],grp3
user93,[email protected],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       [email protected]  grp1  1  pippo2   [email protected] grp1 4  user93  [email protected]  grp1)

print of group[1] variable

pippo1 pippo2 user93

CodePudding user response:

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
  • Related