繁体   English   中英

如何将 Python 功能数据导入 Pandas 数据框

[英]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.

代码:

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()

结果:

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

来自 pandas 的所需数据处理将是:

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

试试这个,但最好的方法是使用python-ldap ,它提供了一个面向对象的 API 来访问 LDAP 并避免字符串解析的开销。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM