我有数千个主机名,我想根据它们的前三个字母将它们分配到不同的列中。我认为如果列表很小并且我知道首字母但我有很大的列表,则可以完成此操作。
我用谷歌搜索了很多,但没有得到任何适当的提示,尝试了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.groupby
将hostnames
列分组到主机值的前三个
字母上,然后使用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/