python-3.x - 如何根据数据框 pandas 的唯一首字母构建新列

标签 python-3.x linux pandas dataframe

我有数千个主机名,我想根据它们的前三个字母将它们分配到不同的列中。我认为如果列表很小并且我知道首字母但我有很大的列表,则可以完成此操作。

我用谷歌搜索了很多,但没有得到任何适当的提示,尝试了df.assign,但这不太适合。

主机名示例:

fox001
fox002
fox003
fox004
fox005
fox006
dbx001
dbx002
dbx003
dbx004
dbx005
dbx006
trd001
trd002
trd003
trd004
trd005
trd006
spl001
spl002
spl003
spl004
spl005
spl006

预期结果:

fox_host   db_host  trd_host spl_host (<-- column names)
fox001     dbx001   trd001   spl001
fox002     dbx002   trd002   spl002
fox003     dbx003   trd003   spl003
fox004     dbx004   trd004   spl004
fox005     dbx005   trd005   spl005
fox006     dbx006   trd006   spl006

我的数据框:

df = pd.read_csv('inventory_hostanme',header=None).rename( columns={ 0:"hostnames"})
print(df)

hostnames
fox001
fox002
fox003
fox004
fox005
fox006
dbx001
dbx002
dbx003
dbx004
dbx005
dbx006
trd001
trd002
trd003
trd004
trd005
trd006
spl001
spl002
spl003
spl004
spl005
spl006

最佳答案

使用Series.groupbyhostnames 列分组到主机值的前三个 字母上,然后使用pd.concat沿着 axis=1 连接每个分组的数据帧,为每个主机创建一个具有单独列的新数据帧:

hosts = pd.concat([
    g.rename(f'{k}_host').reset_index(drop=True)
    for k, g in df['hostnames'].groupby(df['hostnames'].str[:3])], axis=1)

结果:

# print(hosts)

  dbx_host fox_host spl_host trd_host
0   dbx001   fox001   spl001   trd001
1   dbx002   fox002   spl002   trd002
2   dbx003   fox003   spl003   trd003
3   dbx004   fox004   spl004   trd004
4   dbx005   fox005   spl005   trd005
5   dbx006   fox006   spl006   trd006

关于python-3.x - 如何根据数据框 pandas 的唯一首字母构建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62932315/

相关文章:

python - ValueError : malformed string when using ast. literal_eval

python - 在两个列表之间有效地找到 "duplicates",其中字典元素只比较字典字段的一个子集

当我使用 linux 守护进程启动 java 时出现 Java headless 异常

python - 如何在 Python 中从 etc/sysconfig 中检索值

python - 如何使用字符串中的位置来更改 Pandas Dataframe 列中的每个字符串

python - 如果其他功能在 Pandas 数据框中

python - pandas 排序值以获得 groupby 中每一列的前 5 名

Python Pandas 将计算写入新的 Csv 文件

Python3 : How do I import an excel spreadsheet into python project?(我使用 repl.it 网站学习 python3)

linux - QualysGuard API - 语法问题 - 参数 rsa_private_key