簡體   English   中英

數據框到一系列列表

[英]Dataframe to Series of lists

假設我有以下數據框:

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]

您可以嘗試使用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

可以按如下方式進行:

# 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]

你可以用這個

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

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

類似於@jezreal 的解決方案 但是,如果您不期望0值,則可以使用空字符串的固有False -ness:

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

使用刪除空值的列表理解:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM