[英]Pandas extract part of string form a column in a dataframe and store it in a new column
I have the below code to create a dataframe我有以下代码来创建 dataframe
import pandas as pd
df = {'Connection':['Home 10Mbps','Broadband 5 Mbps','128 Kbps Internet','Discounted 512Kbps 2 years contract']}
df = pd.DataFrame (df)
df
I need a way to extract only the bandwidth from column "Connection" and store the result in new column named for example "Bandwidth" to look something like this:我需要一种方法来仅从“连接”列中提取带宽,并将结果存储在名为“带宽”的新列中,如下所示:
Bandwidth带宽
10 Mbps 10 Mbps
5 Mbps 5 Mbps
128 Kbps 128 Kbps
512 Kbps 512 Kbps
Make sure to fill the list with all possible formats确保使用所有可能的格式填写列表
lst = ['10Mbps', '10 Mbps', '5 Mbps', '128 Kbps', '512Kbps', '512 Kbps']
for i in lst:
df.loc[df['Connection'].str.contains(i), 'bandwidth'] = i
# output
Connection bandwidth
Home 10Mbps 10Mbps
Broadband 5 Mbps 5 Mbps
128 Kbps Internet 128 Kbps
Discounted 512Kbps 2 years contract 512Kbps
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.