【问题标题】:Drop Pandas DataFrame rows that contain string of interger删除包含整数字符串的 Pandas DataFrame 行
【发布时间】:2017-03-18 10:21:45
【问题描述】:

我有一个带有列的 pandas DataFrame

[Brand, CPL1, CPL4, Part Number, Calendar Year/Month, value, type]

当它们从 StatsModels X13 中出来时,它们偶尔会有非常大的整数字符串表示,其值在其上下文中没有意义,例如:

[float(1.2), float(1.3), str("63478"), float(1.1)]

如何删除发生这种情况的行?由于它们是整数的字符串表示,我不能转换它们或任何类似的方法。

【问题讨论】:

  • 数据的来源是什么?有缺陷的列(或列中的行)的来源是什么?一些特定的示例数据和/或代码会有所帮助。
  • 起源是一个 SAP Hana xls 文件,它被导入到 DataFrame 中,将每个零件编号展平为一个系列,并从 statsmodels x13 中出来。出自 x13 的系列包含这些违规行为。

标签: python pandas dataframe series


【解决方案1】:

您可以使用boolean indexing 来检查type 是否为string

数据帧

df = pd.DataFrame([[float(1.2), float(1.3), str("63478"), float(1.1)],
                  [float(1.2), float(1.3), float(1.1), str("63478")]]).T

print (df)
      0      1
0    1.2    1.2
1    1.3    1.3
2  63478    1.1
3    1.1  63478

print (df.applymap(lambda x: isinstance(x, str)))
       0      1
0  False  False
1  False  False
2   True  False
3  False   True

print (df.applymap(lambda x: isinstance(x, str)).any(axis=1))
0    False
1    False
2     True
3     True
dtype: bool

print (df[~df.applymap(lambda x: isinstance(x, str)).any(axis=1)])
     0    1
0  1.2  1.2
1  1.3  1.3

系列

s = pd.Series([float(1.2), float(1.3), str("63478"), float(1.1)])
print (s)
0      1.2
1      1.3
2    63478
3      1.1
dtype: object

print (s.apply(lambda x: isinstance(x, str)))
0    False
1    False
2     True
3    False
dtype: bool

print (s[~s.apply(lambda x: isinstance(x, str))])
0    1.2
1    1.3
3    1.1
dtype: object

【讨论】:

    猜你喜欢
    • 2022-08-11
    • 2019-12-02
    • 2019-06-17
    • 2013-10-04
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    相关资源
    最近更新 更多