Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
789 views
in Technique[技术] by (71.8m points)

pandas - series.str.split(expand=True) returns error: Wrong number of items passed 2, placement implies 1

I have a series of web addresses, which I want to split them by the first '.'. For example, return 'google', if the web address is 'google.co.uk'

d1 = {'id':['1', '2', '3'], 'website':['google.co.uk', 'google.com.au', 'google.com']}
df1 = pd.DataFrame(data=d1)
d2 = {'id':['4', '5', '6'], 'website':['google.co.jp', 'google.com.tw', 'google.kr']}
df2 = pd.DataFrame(data=d2)
df_list = [df1, df2]

I use enumerate to iterate the dataframe list

for i, df in enumerate(df_list):
    df_list[i]['website_segments'] = df['website'].str.split('.', n=1, expand=True)

Received error: ValueError: Wrong number of items passed 2, placement implies 1

question from:https://stackoverflow.com/questions/65945651/series-str-splitexpand-true-returns-error-wrong-number-of-items-passed-2-pla

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are splitting the website which gives you a list-like data structure. Think [google, co.uk]. You just want the first element of that list so:

for i, df in enumerate(df_list):
    df_list[i]['website_segments'] = df['website'].str.split('.', n=1, expand=True)[0]

Another alternative is to use extract. It is also ~40% faster for your data:

for i, df in enumerate(df_list):
    df_list[i]['website_segments'] = df['website'].str.extract('(.*?).')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...