![](/img/trans.png)
[英]Removing values form a list in pandas dataframe column based on another list
[英]Return a list with dataframe column values ordered based on another list
我有一個帶有列ah
的 df,我希望創建這些列值的列表,但按照另一個列表 ( list1
) 中值的順序。 list1
對應df中的索引值。
df
a b c d e f g h
list1
[3,1,0,5,2,7,4,6]
想要的清單
['d', 'b', 'a', 'f', 'c', 'h', 'e', 'g']
你可以做df.columns[list1]
:
import pandas as pd
df = pd.DataFrame([], columns=list('abcdefgh'))
list1 = [3,1,0,5,2,7,4,6]
print(df.columns[list1])
# Index(['d', 'b', 'a', 'f', 'c', 'h', 'e', 'g'], dtype='object')
首先得到一個字母表的np.array
arr = np.array(list('abcdefgh'))
或者在您的情況下,您的df
列的列表
arr = np.array(df.columns)
然后使用您的索引作為索引掩碼
arr[[3,1,0]]
出去:
['d', 'b', 'a']
查看
df.columns.to_series()[list1].tolist()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.