【问题标题】:Pandas: iterate over unique values of a column that is already in sorted order using For loopPandas:使用 For 循环遍历已经按排序顺序排列的列的唯一值
【发布时间】:2020-06-10 13:09:54
【问题描述】:

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

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: iterate over unique values of a column that is already in sorted order

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

所以它看起来像这样,带有 2 个函数 f 和 g 在 column[0] 上运行

所以,函数将在循环中定义

col  a  b
f    1  1
g    2  2

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

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

【问题讨论】:

  • for k,v in df.groupby('col0'): print(v)
  • 你能详细说明一下
  • 你应该用实际的列名试试那个命令
  • k 和 v 将是列名,是吗?那么,就我而言,这可能是 index 和 c2 ?
  • k 作为键和 vas 生成的数据帧?

标签: python pandas data-analysis


【解决方案1】:

按字母列对数据框进行分组并解包以获取您的数据框:

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)

【讨论】:

  • 在这种情况下只有2个,这在有数百个键值的情况下是否适用。
  • (key1, df1),(key2, df2) = df.groupby("letter",as_index=False),这条线的LHS是如何工作的。
  • Python 有一个名为 unpacking 的功能,只要它们匹配正确,就可以将 RHS 上的值分配给 LHS 上的变量。对于两个以上的分组,您必须使用 for 循环,正如 @QuangHoang 在 cmets 中解释的那样
猜你喜欢
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 2017-06-02
  • 2019-01-08
  • 2015-11-08
  • 2015-12-16
  • 1970-01-01
  • 2020-03-22
相关资源
最近更新 更多