python - 在 pandas 中显示列

标签 python pandas indexing conditional-statements multiple-columns

我在 pandas 中有一个术语 x 文档矩阵(由 CSV 制成),其形式为:

cheese, milk, bread, butter
0,2,1,0
1,1,0,0
1,1,1,1
0,1,0,1 

因此,如果我说“给我索引 1 和 2 处的列,其中给定行的值都 > 0”。

我想以这样的方式结束:

cheese, milk,
[omitted]
1,1
1,1
[omitted]

这样,我可以对行数/文档数求和并得出频繁项集,即(奶酪,牛奶)--[2/4支持]

我已经尝试过这种方法,如单独的 stackoverflow 线程所示:

fil_df.select([fil_df.columns[1] > 0 and fil_df.columns[2] > 0], [fil_df.columns[1], fil_df.columns[2]])

但遗憾的是它对我不起作用。我收到错误:

TypeError: unorderable types: str() > int()

我不知道如何修复,因为当我从 csv 制作数据帧时,我无法使行的单元格为整数。

最佳答案

您可以使用ilocboolean indexing :

#get 1. and 2. columns
subset = df.iloc[:, [0,1]]
print (subset)
   cheese  milk
0       0     2
1       1     1
2       1     1
3       0     1

#mask
print ((subset > 0))
  cheese  milk
0  False  True
1   True  True
2   True  True
3  False  True

#get all values where True by rows
print ((subset > 0).all(1))
0    False
1     True
2     True
3    False
dtype: bool

#get first and second columns names
print (df.columns[[0,1]])
Index(['cheese', 'milk'], dtype='object')

print (df.ix[(subset > 0).all(1), df.columns[[0,1]]])
   cheese  milk
1       1     1
2       1     1

关于python - 在 pandas 中显示列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39362624/

相关文章:

python - 未知字符排序

python - 这些 X 和 Y 变量如何在线性回归中使用?

python - 结合 Pandas 数据框

Xcode 快速索引永远

c# - 等同于 C# 中枚举类型的索引?

python - 追加数字后矩阵返回 NaN

python - 根据条件更新 Pandas 数据框的值

python - 我想在 PyQt4 的代码中使用键盘快捷键

python - Pandas sort_values 没有正确排序数字

python - 使用列(键)中的信息更改 Pandas 中的索引名称