【问题标题】:Subsetting dataframe on column value does not return any rows在列值上设置数据框不返回任何行
【发布时间】:2021-06-08 22:33:56
【问题描述】:

这个问题与这个有用的答案有关here

情况也一样。我有一个数据框:

print(df)
#      A      B  C   D
# 0  foo    one  0   0
# 1  bar    one  1   2
# 2  foo    two  2   4
# 3  bar  three  3   6
# 4  foo    two  4   8
# 5  bar    two  5  10
# 6  foo    one  6  12
# 7  foo  three  7  14

print(df.loc[df['A'] == 'foo'])

应该给:

A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

但是当我运行它时,我得到一个空数据框。我正在使用的列是数据类型对象,如下所示:

   ColumnA         ColumnB
    117700          []
    467390          []
    467391          []
    467392      ['AF']
    467393    ['AAPL']

我尝试了以下命令。都产生了相同的结果:

df[[ColumnB==['[AAPL]'] for ColumnB in df.ColumnA]]

df[df["ColumnB"] == "AAPL"]

df.query("ColumnB== 'AAPL'")

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    B 列中值的数据类型似乎是list。因此,您不能将它们视为string

    你可以试试这个检查数据类型是不是list

    print(type(df['ColumnB'][0]))
    

    如果是这样,您可以尝试对数据框进行子集化:

    df.loc[df['ColumnB'].apply(lambda x: x[0] if len(x) > 0 else np.nan) == 'AAPL']
    

    关键是使用apply函数为每一行提取列表中的第一个元素,因此这些值变为string

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2019-06-22
      • 2019-03-07
      • 1970-01-01
      • 2018-02-26
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2011-07-24
      相关资源
      最近更新 更多