【问题标题】:turn none into empty list pandas将 none 变成空列表 pandas
【发布时间】:2020-02-04 02:39:42
【问题描述】:
import pandas as pd
Dates = [list(['None','11/04/1911', '03/06/1919']),
          list(['None']),
          list(['01/26/1912', '01/15/1918', '02/06/1917']),
          list(['None'])]
df= pd.DataFrame({'Text':['Hey 10.31.11  22|1|13 03-02-1919 d',
                              'things here 01-23-18 or 03-23-1984 then ',
                                  'stuff 1-22-12 01.11.18 or 2.2.17 so so ',
                          'nothing much'],
                          'ID': ['E1','E2', 'E3', 'E4'],
                  'Dates' : Dates,

                          })

看起来像

                             Dates         ID   Text
0   [None, 11/04/1911, 03/06/1919]          E1  Hey 10.31.11 22|1|13 03-02-1919 d
1   [None]                                  E2  things here 01-23-18 or 03-23-1984 then
2   [01/26/1912, 01/15/1918, 02/06/1917]    E3  stuff 1-22-12 01.11.18 or 2.2.17 so so
3   [None]                                  E4  nothing much

我有以下df。我的目标是替换 ['None'] 例如将 13 排到一个空列表 [] 。我想要的输出是

         Dates   ID Text  New_Date
0                         [None, 11/04/1911, 03/06/1919]           
1                         []                                       
2                         [01/26/1912, 01/15/1918, 02/06/1917]  
3                         []                                        

我看过Check for None in pandas dataframePython: most idiomatic way to convert None to empty string?How to replace None only with empty string using pandas?

我也试过了

df['New_Date] = df['Dates].replace('None', list())

如何实现我想要的输出?

【问题讨论】:

    标签: python-3.x string pandas list replace


    【解决方案1】:

    你可以试试下面的代码,它首先将列表中只有 None 的行转换为 None 字符串,然后用空列表替换它

    cond = df.Dates.str.join(",") == "None"
    df.Dates.loc[cond] = [[] for _ in range(sum(cond))]
    df
    

    【讨论】:

    • 如何使用上面的代码创建一个新列? df['New_Dates'].loc[cond] = [[] for _ in range(sum(cond))]?
    • 您可以复制日期列df["new_dates"] = df.Dates.copy()然后对新列进行操作
    【解决方案2】:

    在 pandas 0.25.1 中使用 explode

    df['New_Date']=df['Dates'].explode().groupby(level=0).apply(lambda x: ','.join(x).split() if x.all() !='None' else [])
    

    0          [None,11/04/1911,03/06/1919]
    1                                    []
    2    [01/26/1912,01/15/1918,02/06/1917]
    3                                    []
    Name: New_Date, dtype: object
    

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 2022-01-22
      • 2018-11-30
      • 1970-01-01
      • 2022-11-26
      • 1970-01-01
      • 2015-03-21
      • 2017-08-06
      相关资源
      最近更新 更多