数据框到一系列列表

时间:2018-12-10 11:27:10

标签: python python-3.x pandas list

说我有以下数据框:

df =pd.DataFrame({'col1':[5,'',2], 'col2':['','',1], 'col3':[9,'','']})  
print(df)

col1 col2 col3
       5    9
 1               
 2     2    1     

是否有一种简单的方法可以将其转换为pd.Series个列表,避免出现空元素?所以:

0 [5,9]
1 [1]
2 [2,2,1]

5 个答案:

答案 0 :(得分:3)

您可以尝试使用df.values

只需取df.values。将它们转换为列表,并使用map删除空元素:

In [2193]: df
Out[2193]: 
  col1 col2 col3
0         5    9
1    1          
2    2    2    1

单线:

In [2186]: pd.Series(df.values.tolist()).map(lambda row: [x for x in row if x != ''])
Out[2186]: 
0       [5, 9]
1          [1]
2    [2, 2, 1]
dtype: object

答案 1 :(得分:2)

可以执行以下操作:

# Break down into list of tuples
records = df.to_records().tolist()

# Convert tuples into lists
series = pd.Series(records).map(list)

# Get rid of empty strings
series.map(lambda row: list(filter(lambda x: x != '', row)))

# ... alternatively
series.map(lambda row: [x for x in row if x != ''])

导致

0    [0, 5, 9]
1          [1]
2    [2, 2, 1]

答案 2 :(得分:2)

类似于@jezreal's solution。但是,如果您不期望使用0值,则可以使用空字符串的固有False性质:

L = [x[x.astype(bool)].tolist() for i, x in df.T.items()]
res = pd.Series(L, index=df.index)

答案 3 :(得分:1)

使用列表理解并删除空值:

L = [x[x != ''].tolist() for i, x in df.T.items()]
s = pd.Series(L, index=df.index)

或通过to_dict使用参数split将值转换为列表:

L = df.to_dict(orient='split')['data']
print (L)
[[5, '', 9], ['', '', ''], [2, 1, '']]

然后删除空值:

s = pd.Series([[y for y in x if y != ''] for x in L], index=df.index)

print (s)
0    [5, 9]
1        []
2    [2, 1]
dtype: object

答案 4 :(得分:1)

您可以使用此

In[1]: [x[x.apply(lambda k: k != '')].tolist() for i, x in df.iterrows()]

Out[1]: [[5, 9], [], [2, 1]]