【问题标题】:How to create a list of lists of integers from DataFrame?如何从 DataFrame 创建整数列表?
【发布时间】:2017-03-07 12:41:24
【问题描述】:

我有数据框:

Values    Values2
1,2,3,4   0,2,3
2,1,0,6   0,0,0
9,8,7,6   1,0,1

我想创建列表列表。我通过以下方式做到这一点:

df[['Values']].values.tolist()

在输出中获取:

[['1,2,3,4'],
 ['2,1,0,6'],
 ['9,8,7,6']]

这是一个字符串,但我需要一个这样的整数列表:

 [[1,2,3,4],
  [2,1,0,6],
  [9,8,7,6]]

我该怎么做?

【问题讨论】:

    标签: python list pandas dataframe


    【解决方案1】:

    您可以使用str.split 以逗号分隔字符串,使用expand=True 这会将每个值分隔到它自己的列中,然后您可以将类型转换为int,然后根据需要获取列表中的值:

    In [109]:
    df['Values'].str.split(',',expand=True).astype(int).values.tolist()
    
    Out[109]:
    [[1, 2, 3, 4], [2, 1, 0, 6], [9, 8, 7, 6]]
    

    分解:

    In [110]:
    df['Values'].str.split(',',expand=True)
    
    Out[110]:
       0  1  2  3
    0  1  2  3  4
    1  2  1  0  6
    2  9  8  7  6
    
    In [111]:    
    df['Values'].str.split(',',expand=True).astype(int).info()
    
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 3 entries, 0 to 2
    Data columns (total 4 columns):
    0    3 non-null int32
    1    3 non-null int32
    2    3 non-null int32
    3    3 non-null int32
    dtypes: int32(4)
    memory usage: 128.0 bytes
    

    要处理NaN/None 值,请使用to_numericstackunstack

    In [114]:
    pd.to_numeric(df['Values'].str.split(',',expand=True).stack(), errors='coerce').unstack().values.tolist()
    
    Out[114]:
    [[1, 2, 3, 4], [2, 1, 0, 6], [9, 8, 7, 6]]
    

    【讨论】:

    • TypeError: long() 参数必须是字符串或数字,而不是'NoneType'
    • 这意味着您的问题中的原始示例数据中没有无效或空字符串,请使用相关示例更新您的问题
    【解决方案2】:

    它们似乎存储为字符串。尝试以下方法(不是很健壮,但根据您的上下文可能没问题):

    slist = df[['Values']].values.tolist()
    ilist = [ [int(s) for s in l[0].split(',')] for l in slist] 
    

    【讨论】:

    • 在决定实施什么之前,我会比较这个解决方案和另一个答案中的性能。这看起来更简单,但没有使用pandas 原生方法。
    猜你喜欢
    • 2019-08-31
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 2021-05-25
    • 2021-08-31
    • 1970-01-01
    • 2020-03-18
    相关资源
    最近更新 更多