首页 > 解决方案 > 如何根据数据框熊猫的唯一首字母构建新列

问题描述

我有数千个主机名,我想根据它们的前三个字母将它们分配到不同的列中。我看到如果它的小列表和我知道首字母但我有巨大的列表可以做到这一点。

我用谷歌搜索了很多,但没有得到任何适当的提示,试过了,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

标签: python-3.xlinuxpandasdataframe

解决方案


用于在主机值的第一个字母上Series.groupby对列进行分组,然后用于连接每个分组的数据帧,为每个主机创建一个具有单独列的新数据帧:hostnamesthreepd.concataxis=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

推荐阅读