Karn Kumar
Karn Kumar

Reputation: 8816

How to import Python Fuction data into Pandas Data-frame

I have a code below which is just fetching the data from the ldapsearch command, now i am thinking about to use pandas to get data into a desired format but i am not getting how i can access the python function data into Pandas DataFrame.

Code :

import subprocess

def UserID():
    LDP = "ldapsearch -h ldap.example.com -xLLLb 'ou=Personal,ou=People,ou=udalt' uid fullName"
    proc = subprocess.Popen(LDP, shell=True, stdout=subprocess.PIPE)
    info_str = proc.stdout.read().decode('utf8')
    str_info = info_str.splitlines()
    prefixes = ["uid:", "fullName:"]
    for line in str_info:
        if line.startswith(tuple(prefixes)):
            lines = line
            for line in lines.splitlines():
                     print(line, end=' ' if line.startswith("uid:")  else "\n")
UserID()

Result:

uid: khati06610 fullName: Anik sa
uid: khati06648 fullName: Vikur Doom
uid: khati06663 fullName: Gopi sa
uid: khati06718 fullName: Jeff kana
uid: khati10131 fullName: Peter j
uid: khati10152 fullName: Mie sean

Desired Data From pandas Processing will be :

User ID        User Name
khati06610    Anik sa 
khati06648    Vikur Doom
khati06663    Gopi sa 
khati06718    Jeff kana
khati10131    Peter j 
khati10152    Mie sean

Upvotes: 0

Views: 106

Answers (1)

sushanth
sushanth

Reputation: 8302

try this, but the preferable way would be to use python-ldap which provides an object-oriented API to access LDAP & avoid's the overhead of string parsing.

import re
import pandas as pd

search_ = re.compile("uid:\s(.*)\sfullName:\s(.*)")

print(
    pd.DataFrame(
        [{"User ID": u, "User Name": n} for u, n in search_.findall(line)]
    )
)

      User ID   User Name
0  khati06610     Anik sa
1  khati06648  Vikur Doom
2  khati06663     Gopi sa
3  khati06718   Jeff kana
4  khati10131     Peter j
5  khati10152    Mie sean

Upvotes: 2

Related Questions