python - 删除行值类似于 '[ ]' 的数据框列

标签 python pandas dataframe

在我的数据框中,有几行的值类似于“[]”,我想删除整列,如何完成?

Data Frame Image 这是我的代码

import re

for i, row in df.iterrows():
    for j, column in row.iteritems():
      #print(column)
      #print(j)
      t = re.findall("\[\]", column)
      if t:
        df.drop(j, axis=1, inplace=True)
      else:
        print('Nothing'+j)

这是我得到的错误

TypeError                                 Traceback (most recent call last)
<ipython-input-72-927572386a36> in <module>
      3     #print(column)
      4     #print(j)
----> 5         t = re.findall("\[\]", column)
      6         if t:
      7             df.drop(j, axis=1, inplace=True)

/anaconda3/lib/python3.7/re.py in findall(pattern, string, flags)
    221 
    222     Empty matches are included in the result."""
--> 223     return _compile(pattern, flags).findall(string)
    224 
    225 def finditer(pattern, string, flags=0):

TypeError: expected string or bytes-like object

最佳答案

我相信您需要将值强制转换为 bool 值并仅使用 DataFrame.all 过滤 True 的列:

df = pd.DataFrame({'a':[[], [], ['d']],
                   'b':[['d'], ['a'], ['d']],
                   'c':[[], [], []]})

print (df)
     a    b   c
0   []  [d]  []
1   []  [a]  []
2  [d]  [d]  []

df1 = df.loc[:, df.astype(bool).all()]
print (df1)
     b
0  [d]
1  [a]
2  [d]

详细信息:

print (df.astype(bool))
       a     b      c
0  False  True  False
1  False  True  False
2   True  True  False

关于python - 删除行值类似于 '[ ]' 的数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55449286/

相关文章:

python - nltk.download() 在 OS X 上挂起

python - python请求数据中发送 "\r\n"符号

python - 如何摆脱行号,pd.read_excel?

r - 将 data.frame 列从因子转换为字符

python - 如何按键划分两个DataFrame

python - map、lambda 和 append.. 为什么不起作用?

python - 如何使用 opencv python 调整亮度、对比度和振动度?

python - 尝试使用 Pandas 系列的 datetime64 对象检查数据频率

python - 如何在 Pandas 中获得同一条船连续安装的最旧部分安装?

python - Pandas 列在附加到新数据框后已排序