简体   繁体   中英

Pandas: unpack column in tuple length 1

I have a DataFrame df with many column values like so:

index   Column1
0       [data1]
1       [data2]
2       [data3]
3       [data4]
4       [data5]
5       [data6]

I am looking for a simple Pandas or NumPy command to convert it to a DataFrame like this:

index   Column1
0       data1
1       data2
2       data3
3       data4
4       data5
5       data6

Currently I am doing:

df[Column1] = [each[0] for each in df[Column1]]

but this would require me to loop through all the columns.

You can use the str accessor to get the element out of the list:

df['Column1'] = df['Column1'].str[0]

For instance:

>>> df
   Column1
0  [item1]
1  [item2]
2  [item3]

>>> df['Column1'].str[0]
0    item1
1    item2
2    item3

The primary use of str is to open up a column or Series to Pandas' vectorised string operations, but it can also be useful if the values in the column are Python lists.

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