【问题标题】:How to convert the "rows" of a pandas Series into columns of a DataFrame?如何将熊猫系列的“行”转换为 DataFrame 的列?
【发布时间】:2024-01-24 03:33:01
【问题描述】:

我有以下熊猫系列,ser1 形状 (100,)。

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

这个Series中每个ndarray的长度是150000,其中每个元素都是一个字符。

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

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

我想将此熊猫系列转换为熊猫数据框,这样熊猫系列“行”的每个元素都是一个数据框列。也就是说,该 Series 数组的每个元素都是一个单独的列。在这种情况下,ser1 将有 150000 列。

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
........

如何以这种方式将 pandas Series 转换为 DataFrame?

最明显的想法是做

df_ser = ser1.to_frame

但这不会将元素分成单独的 Dataframe 列:

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

不知何故,人们会遍历“系列行”的每个元素并创建一列,尽管我不确定这在计算上有多可行。 (这不是很pythonic。)

如何做到这一点?

【问题讨论】:

    标签: python pandas indexing dataframe


    【解决方案1】:

    考虑一个示例系列ser1

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

    在将字符串设为字符列表后使用pd.Series 应用。

    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
    

    【讨论】:

    • 这对于我这个大小的数据集非常有效。感谢您的帮助!
    【解决方案2】:

    我的方法是将数据作为 numpy 数组处理,然后将最终产品存储在 pandas DataFrame 中。但总的来说,在数据框中创建 100k+ 列似乎相当慢。

    与 piRSquareds 解决方案相比,我的解决方案并没有更好,但我想我还是会发布它,因为它是一种不同的方法。

    样本数据

    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]))
    

    输出:

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

    解决方案

    # 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)
    

    运行时

    由于 piRSquared 已经发布了解决方案,我应该包括运行时分析。

    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])
    

    输出:

    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
    

    【讨论】:

      最近更新 更多