【问题标题】:extracting specifiv values from pandas dataframe column从熊猫数据框列中提取特定值
【发布时间】:2018-04-29 20:38:19
【问题描述】:

我在 pandas 数据框列中有如下数据:

[2, 4]
[3, 4]
[1, 4]
[0, 0] 

我希望数据的形式为

col_1  col_2
2      4
3      4
1      4
0      0

谁能帮助我如何获取上述表格中的数据。

【问题讨论】:

    标签: python pandas dataframe jupyter-notebook


    【解决方案1】:

    如果列表都具有相同数量的元素,您可以使用 .tolist() 轻松完成此操作

    import pandas as pd   
    df = pd.DataFrame({'val1': [[2, 4], [3, 4], [1, 4], [0, 0]]})   
    
    df[['col_1', 'col_2']] = pd.DataFrame(df.val1.tolist())
         val1  col_1  col_2
    0  [2, 4]      2      4
    1  [3, 4]      3      4
    2  [1, 4]      1      4
    3  [0, 0]      0      0
    

    【讨论】:

    • 正是我需要的。谢谢ALollz
    【解决方案2】:

    ALollz 给出了更好的答案,但鉴于标题是关于提取特定值,这里有一个更直接和说明性(但效率较低)的方法:

    import pandas as pd
    
    df = pd.DataFrame()
    df["cur"] = [[2,4],[3,4],[1,4],[0,0]]
    print(df) # This is what you have
    
    # You can access elements by df[<column>][<row>][<list index>]
    # This is looping across all rows of the "cur" column, and pulling out
    #    the values at the 0th and 1st index.
    df["col_1"] = [pair[0] for pair in df["cur"]]
    df["col_2"] = [pair[1] for pair in df["cur"]]
    print(df)
    

    输出

    电流 0 [2, 4] 1 [3, 4] 2 [1, 4] 3 [0, 0] 当前 col1 col2 0 [2, 4] 2 4 1 [3, 4] 3 4 2 [1, 4] 1 4 3 [0, 0] 0 0

    【讨论】:

      【解决方案3】:

      另一种方法是使用applypd.Series

      df = pd.DataFrame({'val1': [[2, 4], [3, 4], [1, 4], [0, 0]]})   
      
      df['val1'].apply(pd.Series).rename(columns=lambda x: x + 1).add_prefix('col_')
      

      输出:

         col_1  col_2
      0      2      4
      1      3      4
      2      1      4
      3      0      0
      

      或类似于@ALollz,但更强大,可以捕获任意数量的列。

      pd.DataFrame(df['val1'].tolist())\
        .rename(columns=lambda x: x + 1)\
        .add_prefix('col_')
      

      【讨论】:

        猜你喜欢
        • 2020-10-30
        • 1970-01-01
        • 1970-01-01
        • 2017-06-26
        • 2013-06-29
        • 1970-01-01
        • 2018-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多