【问题标题】:convert dataframe column of list to comma separated string in python在python中将列表的数据框列转换为逗号分隔的字符串
【发布时间】:2021-11-02 02:22:14
【问题描述】:

我有一个数据框df1

id     city       year
1       LA        [2012, 2013, 2014, 2015, 2026]
2       FL        []
3       TX        [2012, 2013, 2014]
4       NY        [2012]

如何将包含列表的列year 转换为逗号分隔的字符串?

想要的结果:

id     city       year
1      LA         2012, 2013, 2014, 2015, 2016
2      FL         none
3      TX         2012, 2013, 2014
4      NY         2012

注意:year 列的数据类型现在是字符串。

【问题讨论】:

    标签: python pandas list dataframe


    【解决方案1】:

    试试explode 然后groupby

    df.year = df.year.explode().astype(str).groupby(level=0).agg(', '.join)
    

    【讨论】:

      【解决方案2】:

      另一种方法:

      df.loc[:, 'year'] = df.year.apply(str).replace('[\[\]]', '', regex=True)
      

      【讨论】:

        【解决方案3】:

        试试:

        df["year"] = df["year"].apply(lambda x: ", ".join(map(str, x)))
        print(df)
        

        打印:

           id city                          year
        0   1   LA  2012, 2013, 2014, 2015, 2026
        1   2   FL                              
        2   3   TX              2012, 2013, 2014
        3   4   NY                          2012
        

        或者对于none字符串:

        df["year"] = (
            df["year"].apply(lambda x: ", ".join(map(str, x))).replace("", "none")
        )
        print(df)
        

        打印:

           id city                          year
        0   1   LA  2012, 2013, 2014, 2015, 2026
        1   2   FL                          none
        2   3   TX              2012, 2013, 2014
        3   4   NY                          2012
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-02-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-17
          • 2018-06-20
          相关资源
          最近更新 更多