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



>我已经以排序的方式构造了一个数据帧,现在需要编写一个代码来迭代每个唯一的项目 所以说数据集是

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

Id 需要代码遍历 df,以便使用 column[0] 中的唯一值形成 2 个新的 df。

a,1
a,2
a,3

b,1
b,2

这里做了类似的事情:P andas:遍历已经按排序顺序排列的列的唯一值

但是 id 需要一个 for 循环来获取我的函数在形成的每个可能的数据帧上运行后的输出。

所以它看起来像这样 wwith 2 个功能 f 和 g 在列上运行[0]

因此,函数将在循环中定义

col  a  b
f    1  1
g    2  2

尝试使用(AG是带有键值的列的名称(:

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

按字母列对数据帧进行分组并解压缩以获取数据帧:

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)

最新更新