gpt4 book ai didi

python - 从另一列的值创建新列

转载 作者:行者123 更新时间:2023-11-30 21:51:46 25 4
gpt4 key购买 nike

我在数据框中有一列包含不同的字符串。

Additional Information  |  
IP=192.168.1.1, MAC ADDR=00:0a:95:9d:68:16, USER=kwfinn
IP=192.168.0.1, MAC ADDR=00:0a:95:9d:68:17, USER=wattray
Undefined System Error
Specific groupname=CUSTGR1
IP=192.168.1.2, MAC ADDR=00:1B:44:11:3A:B7, USER=stwnck

我想要做的是使用上面列中的相应值创建新列“IP 地址”和“MAC 地址”。

因此预期的输出如下所示:

Additional Information                                  |IP Address  | MAC Address     |    
IP=192.168.1.1, MAC ADDR=00:0a:95:9d:68:16, USER=kwfinn |192.168.1.1 |00:0a:95:9d:68:16|
IP=192.168.0.1, MAC ADDR=00:0a:95:9d:68:17, USER=wattray|192.168.0.1 |00:0a:95:9d:68:17|
Undefined System Error | | |
Specific groupname=CUSTGR1 | | |
IP=192.168.1.2, MAC ADDR=00:1B:44:11:3A:B7, USER=stwnck |192.168.1.2 |00:1B:44:11:3A:B7|

问题是,我无法处理不包含 IP 和 MAC 的行。我尝试使用 np.where 进行拆分以及查找部分匹配项,但没有成功。

最佳答案

想法是使用列表理解和过滤,如果不缺少值或 None 且存在 =,则传递给 DataFrame 构造函数并最后使用DataFrame.join原文:

L = [dict(y.split("=") for y in v.split(", "))  
if pd.notna(v) and ('=' in v) and (', ' in v)
else {}
for v in df['Additional Information']]

df1 = pd.DataFrame(L, index=df.index)
print (df1)
IP MAC ADDR USER
0 192.168.1.1 00:0a:95:9d:68:16 kwfinn
1 192.168.0.1 00:0a:95:9d:68:17 wattray
2 NaN NaN NaN
3 NaN NaN NaN
4 192.168.1.2 00:1B:44:11:3A:B7 stwnck

df = df.join(df1[['IP','MAC ADDR']])
print (df)
Additional Information IP \
0 IP=192.168.1.1, MAC ADDR=00:0a:95:9d:68:16, US... 192.168.1.1
1 IP=192.168.0.1, MAC ADDR=00:0a:95:9d:68:17, US... 192.168.0.1
2 Undefined System Error NaN
3 Specific groupname=CUSTGR1 NaN
4 IP=192.168.1.2, MAC ADDR=00:1B:44:11:3A:B7, US... 192.168.1.2

MAC ADDR
0 00:0a:95:9d:68:16
1 00:0a:95:9d:68:17
2 NaN
3 NaN
4 00:1B:44:11:3A:B7

关于python - 从另一列的值创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60054915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com