简体   繁体   English

如何从DataFrame创建整数列表?

[英]How to create a list of lists of integers from DataFrame?

I have Data Frame: 我有数据框:

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

I want to create list of lists. 我想创建列表列表。 I do that in following way: 我这样做是这样的:

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

In output a get: 在输出中得到:

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

It's a strings but I need a lists of integer like that: 这是一个字符串,但我需要一个像这样的整数列表:

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

How can I do that? 我怎样才能做到这一点?

It seems they are stored as a string. 它们似乎存储为字符串。 Try the following (not very robust, but depending on your context it can be ok): 尝试以下(不是非常强大,但根据您的上下文,它可以是正常的):

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

You can use str.split to split the string on comma, with expand=True this will separate each value into it's own column, you can then convert the type to int and then get the values in a list as desired: 您可以使用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]]

Breaking this down: 打破这个:

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

To handle NaN/None values use to_numeric with stack and unstack : 为了处理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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM