user17983408
user17983408

Reputation: 15

Python dataframe list-column splitting

I have a dataframe with one of the columns being a list like so:

RefID Ref
Ref1 (baby, 60, 0)
Ref2 (something, 90, 2)

I wanted to extract this list as separate fields, as in this code:

df['MatchWord'], df['Prox'], df['MatchID'] = df.Ref.str

But I get the "FutureWarning: Columnar iteration..." error. How else can I split this list-column?

Upvotes: 1

Views: 192

Answers (2)

Corralien
Corralien

Reputation: 120439

Use pd.DataFrame.from_records and join:

cols = ['MatchWord', 'Prox', 'MatchID']
out = df.join(pd.DataFrame.from_records(df['Ref'], index=df.index, columns=cols))
print(out)

# Output
  RefID                 Ref  MatchWord  Prox  MatchID
0  Ref1       (baby, 60, 0)       baby    60        0
1  Ref2  (something, 90, 2)  something    90        2

Upvotes: 1

mozway
mozway

Reputation: 261015

You can apply(pd.Series). This will unpack the items as columns:

df['Ref'].apply(pd.Series, index=['MatchWord', 'Prox', 'MatchID'])

Or use the DataFrame constructor:

pd.DataFrame(df['Ref'].to_list(), columns=['MatchWord', 'Prox', 'MatchID'])

Output:

   MatchWord  Prox  MatchID
0       baby    60        0
1  something    90        2

Upvotes: 1

Related Questions