【发布时间】:2016-07-20 17:29:04
【问题描述】:
我有一个如下的数据框
df:
ID color finish duration
A1 black smooth 12
A2 white matte 8
A3 blue smooth 20
A4 green matte 10
B1 black smooth 12
B2 white matte 8
B3 blue smooth
B4 green 10
C1 black smooth
C2 white matte 8
C3 blue smooth
C4 green 10
我想根据特定条件生成此数据帧的子集。例如,
color= black,finish = smooth,duration = 12,我得到以下数据框。
ID color finish duration score
A1 black smooth 12 1
B1 black smooth 12 1
color= blue,finish = smooth,duration = 20,我得到以下数据框。
ID color finish duration score
A3 blue smooth 20 1
B3 blue smooth 0.666667
C3 blue smooth 0.666667
分数计算为填充的列数/总列数。 我想在熊猫数据框中循环这个。 以下代码适用于我的 2 列。
list2 = list(df['color'].unique())
list3 = list(df['finish'].unique())
df_final = pd.DataFrame()
for i in range(len(list2)):
for j in range(len(list3)):
print 'Current Attribute Value:',list2[i],list3[j]
gbl["df_"+list2[i]] = df[df.color == list2[i]]
gbl["df_" + list2[i] + list3[j]] =
gbl["df_"+list2[i]].loc[gbl["df_"+list2[i]].finish == list3[j]]
gbl["df_" + list2[i] + list3[j]]['dfattribval'] = list2[i] + list3[j]
df_final = df_final.append(gbl["df_" + list2[i] + list3[j]], ignore_index=True)
但是,我无法在列名上循环。我想做的是,
lista = ['color','finish']
df_final = pd.DataFrame()
for a in range(len(lista)):
for i in range(len(list2)):
for j in range(len(list3)):
print 'Current Attribute Value:',lista[a],list2[i],lista[a+1],list3[j]
gbl["df_"+list2[i]] = df[df.lista[a] == list2[i]]
gbl["df_" + list2[i] + list3[j]] = gbl["df_"+list2[i]].loc[gbl["df_"+list2[i]].lista[a+1] == list3[j]]
gbl["df_" + list2[i] + list3[j]]['dfattribval'] = list2[i] + list3[j]
df_final = df_final.append(gbl["df_" + list2[i] + list3[j]], ignore_index=True)
我得到了明显的错误 -
AttributeError: 'DataFrame' 对象没有属性 'lista'。
任何人都知道如何遍历列名和值。非常感谢!
【问题讨论】:
-
这个问题前后矛盾的地方太多了。当您说列时,您是指行吗?
number of columns populated/total number of columns。当您显示color= blue、finish = smooth、duration = 20时,您会显示 3 行,其中两行没有持续时间 20。我不知道您需要如何解决这个问题。 -
另外,真正的最终结果是什么:单独的 dfs 还是一个最终附加的 df?一个简单的
groupby()的颜色和光洁度就可以实现你的score,而不需要分离dfs。 -
@piRSquared,关于您的第一个问题,我正在寻找列数,或者更具体地说是填充的单元格。例如,在第二个表中,第二行和第三行不填充持续时间。因此,分数是 2 / 3。关于第二个问题,如果您可以将其想象为在 excel 中过滤,我首先按颜色过滤,然后按完成,最后按持续时间。然后我得到所需的输出。
-
原谅我,不确定您是否回答了我的问题,但期望的输出是什么?只有一个df还是多个df?您可以按这些不同的维度进行分组,而无需拆分。请编辑给我们看。