Osca
Osca

Reputation: 1694

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

Upvotes: 0

Views: 271

Answers (1)

noah
noah

Reputation: 2786

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('(.*?)\.')

Upvotes: 1

Related Questions