简体   繁体   中英

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

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

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

but id need a for loop to get the output for my function after its run over every possible dataframe formed.

so itd look something like this 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 ):

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

Group the dataframe by the letter column and unpack to get your dataframes:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM