ShanZhengYang
ShanZhengYang

Reputation: 17631

How to convert the "rows" of a pandas Series into columns of a DataFrame?

I have the following pandas Series, ser1 of shape (100,).

import pandas as pd
ser1 = pd.Series(...)
print(len(ser1)) 
##  prints (100,)

The length of each ndarray within this Series is length 150000, where each element is a character.

len(print(ser1[0]))
##  prints 150000

ser1.head()
sample1       xhtrcuviuvjhgfsrexvuvhfgshgckgvghfsgfdsdsg...
sample2       jhkjhgkjvkjgfjyqerwqrbxcvmkoshfkhgjknlkdfk...
sample3       sdfgfdxcvybnjbvtcyuikjhbgfdftgyhujhghjkhjn...
sample4       bbbbbbadfashdwkjhhguhoadfopnpbfjhsaqeqjtyi...
sample5       gfjyqedxcvrexvuvcvmkoshdftgyhujhgcvmkoshfk...
dtype: object

I would like to covert this pandas Series into a pandas DataFrame such that each element of this pandas Series "row" is a DataFrame column. That is, each element of that Series array would be an individual column. In this case, ser1 would have 150000 columns.

print(type(df_ser1)) # DataFrame of ser1
## outputs <class 'pandas.core.frame.DataFrame'>
df_ser1.head()
     samples    char1    char2    char3    char4    char5    char6
0    sample1    x        h        t        r        c        u
1    sample2    j        h        k        j        h        g
2    sample3    s        d        f        g        f        d
3    sample4    b        b        b        b        b        b
........

How would one convert a pandas Series to a DataFrame in this way?

The most obvious idea would be to do

df_ser = ser1.to_frame

but this does not separate elements into individual Dataframe columns:

df_ser = ser1.to_frame
df_ser.head()
                                                       0
sample1       xhtrcuviuvjhgfsrexvuvhfgshgckgvghfsgfdsdsg...
sample2       jhkjhgkjvkjgfjyqerwqrbxcvmkoshfkhgjknlkdfk...
sample3       sdfgfdxcvybnjbvtcyuikjhbgfdftgyhujhghjkhjn...
......

Somehow, one would iterate though each element of the "Series row" and create a column, though I'm not sure how computationally feasible that is. (It's not very pythonic.)

How would one do this?

Upvotes: 3

Views: 5166

Answers (2)

Filip Kilibarda
Filip Kilibarda

Reputation: 2668

My approach would be to work with the data as numpy arrays, then store the final product in a pandas DataFrame. But overall, it seems like creating 100k+ columns in a dataframe is pretty slow.

Compared to piRSquareds solution, mine isn't really any better, but I figured I'd post it anyway since it's a different approach.

Sample Data

import pandas as pd
from timeit import default_timer as timer

# setup some sample data
a = ["c"]
a = a*100
a = [x*10**5 for x in a]
a = pd.Series(a)
print("shape of the series = %s" % a.shape)
print("length of each string in the series = %s" % len(a[0]))

Output:

shape of the series = 100
length of each string in the series = 100000

Solution

# get a numpy array representation of the pandas Series
b = a.values
# split each string in the series into a list of individual characters
c = [list(x) for x in b]
# save it as a dataframe
df = pd.DataFrame(c)

Runtime

As piRSquared already posted a solution, I should include runtime analysis.

execTime=[]
start = timer()
# get a numpy array representation of the pandas Series
b = a.values
end = timer()
execTime.append(end-start)

start = timer()
# split each string in the series into a list of individual characters
c = [list(x) for x in b]
end = timer()
execTime.append(end-start)

start = timer()
# save it as a dataframe
df = pd.DataFrame(c)
end = timer()
execTime.append(end-start)

start = timer()
a.apply(lambda x: pd.Series(list(x))).rename(columns=lambda x: 'char{}'.format(x + 1))
end = timer()
execTime.append(end-start)
print("get numpy array                      = %s" % execTime[0])
print("Split each string into chars runtime = %s" % execTime[1])
print("Save 2D list as Dataframe runtime    = %s" % execTime[2])
print("piRSquared's solution runtime        = %s" % execTime[3])

Output:

get numpy array                      = 7.788003131281585e-06
Split each string into chars runtime = 0.17509693499960122
Save 2D list as Dataframe runtime    = 12.092364584001189
piRSquareds solution runtime         = 13.954442440001003

Upvotes: 2

piRSquared
piRSquared

Reputation: 294258

Consider a sample series ser1

ser1 = pd.Series(
    'abc def ghi'.split(),
    'sample1 sample2 sample3'.split())

Apply with pd.Series after having made the string a list of chars.

ser1.apply(lambda x: pd.Series(list(x))) \
    .rename(columns=lambda x: 'char{}'.format(x + 1))

        char1 char2 char3
sample1     a     b     c
sample2     d     e     f
sample3     g     h     i

Upvotes: 2

Related Questions