简体   繁体   中英

Extract an integer value from a string that is in a list that is in a dataframe column in python?

I have a dataframe that contains a column "Tickets" that now contains a single integer value as a string inside of a series.

print(type(train_tickets.Ticket))

<class 'pandas.core.series.Series>
train_tickets["Ticket"].head()

# Returns
1    [211536]
2    [112053]
3      [6607]
4    [111369]
5    [370376]

What I want:

1    211536
2    112053
3      6607
4    111369
5    370376

I can convert the individual numbers using this, but I haven't been able to get a loop or lambda function to return what I'm expecting.

int(train_tickets["Ticket"][0][0])

# returns 
21171

I have tried this loop (and associated lambda format)

for row in train_tickets["Ticket"]:
    Y = int(train_tickets["Ticket"][row][0])

but it's returning a Key Error, self._get_with(key) How can I do this with.apply(lambda ) or a loop of some sort?

Try:

train_tickets.Ticket = train_tickets.Ticket.str[0]

If values inside the list are of type string you can do:

train_tickets.Ticket = train_tickets.Ticket.str[0].astype(int)

To convert them to integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM