python-3.x - 如何根据数据框熊猫的唯一首字母构建新列
问题描述
我有数千个主机名,我想根据它们的前三个字母将它们分配到不同的列中。我看到如果它的小列表和我知道首字母但我有巨大的列表可以做到这一点。
我用谷歌搜索了很多,但没有得到任何适当的提示,试过了,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
three
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
推荐阅读
- solidity - 在我的合约中运行 new() 会增加 20K 的合约大小?
- java - 将对象元素插入对象数组
- javascript - 如何在后台的tizen Web应用程序中每15分钟振动一次?
- python - 如何使用 python 解决 DNN(深度神经网络)模型中的 ValueError?
- javascript - 再次按下输入/按钮后重置 div/警报?
- c# - 如何在 ListView xamarin 上返回已处理的集合
- javascript - 如果从扩展反序列化为具体对象
- pytorch - 如何通过torch.nn.conv1d更简单地将张量(形状:[a,b,c])卷积到张量(形状:[1,b,1])?
- mongodb - 如何仅在 mongodb 中查找所有嵌入式属性匹配的嵌入式事件?
- ios - 更新到 iOS15 后的内部应用程序:需要更新应用程序