简体   繁体   中英

How to get table from table contains list column of strings by sql or python

I have table as following

eventID countries
aaffff. Japan, US, Frunce
aafggg. Japan, Frunce

i want to get new table

eventID countries
aaffff. Japan
aaffff. US
aaffff. Frunce
aafggg. Japan
aafggg. Frunce

As i dont know how much strings i will have in the column countries the function Split_part will not assist me. if there is better way to do it by python i will be glad to hear.

In [24]: a = [{"eventID":"aaffff","countries":"Japan, US, Frunce"},{"eventID":"aafggg","countries":"Japan, Frunce"}]

In [25]: df = pd.DataFrame(a)

In [26]: df
Out[26]:
  eventID          countries
0  aaffff  Japan, US, Frunce
1  aafggg      Japan, Frunce

In [28]: df["countries"] = df["countries"].str.split(",")

In [29]: df
Out[29]:
  eventID              countries
0  aaffff  [Japan,  US,  Frunce]
1  aafggg       [Japan,  Frunce]

In [30]: df.explode("countries")
Out[30]:
  eventID countries
0  aaffff     Japan
0  aaffff        US
0  aaffff    Frunce
1  aafggg     Japan
1  aafggg    Frunce

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