簡體   English   中英

Pandas:使用 For 循環迭代已排序的列的唯一值

[英]Pandas: iterate over unique values of a column that is already in sorted order using For loop

我已經以排序的方式構建了一個 dataframe,現在需要編寫一個代碼來遍歷每個唯一的 Item 所以說數據集是

a,1
a,2
a,3
b,1
b,2

我需要代碼以這樣一種方式遍歷 df,即使用列 [0] 中的唯一值形成 2 個新的 df。

a,1
a,2
a,3

b,1
b,2

此處進行了類似的操作: Pandas:迭代已排序的列的唯一值

但 id 需要一個 for 循環來為我的 function 獲取 output 在它運行完所有可能的 dataframe 之后。

所以它看起來像這樣 wwith 2 functoions f and g running over column[0]

所以,函數將在循環中定義

col  a  b
f    1  1
g    2  2

嘗試使用( AG 是具有鍵值的列的名稱):

for AG, V in df.groupby[('AG')]:print(V)

按字母列對 dataframe 進行分組並解壓以獲取數據幀:

df = pd.read_clipboard(sep=',', header=None,names=['letter','number'])

 #unpack dataframe
 #the groupby holds the group key, with the grouped variables
 #in this case we know that there are only two groupings (a and b)
(key1, df1),(key2, df2) = df.groupby("letter",as_index=False)

暫無
暫無

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

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