简体   繁体   中英

Splitting string inside pandas dataframe

I have this column in my dataframe which has numbers in a string like "6,22,67,82" for example. I want to split this strings into arrays of integers and keep the arrays in the dataframe.

  h['htgt']=h['htgt'].split()

This does not work because it tries to split the whole series.

You can use pd.Series.str.split with expand=True and then convert to int . Assumes you have an equal number of numbers in each string.

h = pd.DataFrame({'htgt': ['6,22,67,82', '12,45,65,14', '54,15,9,94']})

res = h['htgt'].str.split(',', expand=True).astype(int)

print(res)

    0   1   2   3
0   6  22  67  82
1  12  45  65  14
2  54  15   9  94

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