[英]Python: Create structured numpy structured array from two columns in a DataFrame
如何從DataFrame中的兩列創建結構化數組? 我試過這個:
df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b'])
df
a b
0 1 2
1 10 20
x = np.array([([val for val in list(df['a'])],
[val for val in list(df['b'])])])
但這給了我這個:
array([[[ 1, 10],
[ 2, 20]]])
但我想要這個:
[(1,2),(10,20)]
謝謝!
有幾種方法。 相對於常規NumPy陣列,您可能會遇到性能和功能損失。
您可以使用index=False
pd.DataFrame.to_records
。 從技術上講,這是一個記錄陣列 ,但出於許多目的,這就足夠了。
res1 = df.to_records(index=False)
print(res1)
rec.array([(1, 2), (10, 20)],
dtype=[('a', '<i8'), ('b', '<i8')])
手動,您可以通過逐行轉換為tuple
來構造結構化數組,然后為dtype
參數指定元組列表。
s = df.dtypes
res2 = np.array([tuple(x) for x in df.values], dtype=list(zip(s.index, s)))
print(res2)
array([(1, 2), (10, 20)],
dtype=[('a', '<i8'), ('b', '<i8')])
有什么不同?
很少。 recarray
是的子類ndarray
,常規NumPy的陣列型。 另一方面,第二個例子中的結構化數組是ndarray
類型。
type(res1) # numpy.recarray
isinstance(res1, np.ndarray) # True
type(res2) # numpy.ndarray
主要區別是記錄數組有助於屬性查找,而結構化數組將產生AttributeError
:
print(res1.a)
array([ 1, 10], dtype=int64)
print(res2.a)
AttributeError: 'numpy.ndarray' object has no attribute 'a'
使用list comprehension將嵌套list
轉換為tuple
:
print ([tuple(x) for x in df.values.tolist()])
[(1, 2), (10, 20)]
細節 :
print (df.values.tolist())
[[1, 2], [10, 20]]
編輯:你可以轉換為to_records
然后轉換為np.asarray
,檢查鏈接 :
df = pd.DataFrame(data=[[True, 1,2],[False, 10,20]], columns=['a','b','c'])
print (df)
a b c
0 True 1 2
1 False 10 20
print (np.asarray(df.to_records(index=False)))
[( True, 1, 2) (False, 10, 20)]
這是一個單行:
list(df.apply(lambda x: tuple(x), axis=1))
要么
df.apply(lambda x: tuple(x), axis=1).values
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.