简体   繁体   English

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

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

I have constructed a dataframe in a sorted manner, and now need to write a code that iterates over Each unique Item So say the data set is我已经以排序的方式构建了一个 dataframe,现在需要编写一个代码来遍历每个唯一的 Item 所以说数据集是

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

Id need the code to loop over the df in such a way that 2 new dfs are formed using the unique values in column[0].我需要代码以这样一种方式遍历 df,即使用列 [0] 中的唯一值形成 2 个新的 df。

a,1
a,2
a,3

and

b,1
b,2

Something similar is done here: Pandas: iterate over unique values of a column that is already in sorted order此处进行了类似的操作: Pandas:迭代已排序的列的唯一值

but id need a for loop to get the output for my function after its run over every possible dataframe formed.但 id 需要一个 for 循环来为我的 function 获取 output 在它运行完所有可能的 dataframe 之后。

so itd look something like this wwith 2 functoions f and g running over column[0]所以它看起来像这样 wwith 2 functoions f and g running over column[0]

so, the functions would be defined within the loop所以,函数将在循环中定义

col  a  b
f    1  1
g    2  2

Tried using( AG is the name of the column with Key values ):尝试使用( AG 是具有键值的列的名称):

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

Group the dataframe by the letter column and unpack to get your dataframes:按字母列对 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