【问题标题】:How to compare columns with both strings and integers? Python Pandas如何比较具有字符串和整数的列?蟒蛇熊猫
【发布时间】:2019-01-07 18:50:00
【问题描述】:

我有一个带有两列的 pandas DataFrame,一列同时包含整数(1-23)和字符串(X 或 Y),另一列仅包含数字。我想比较值是否相等。我尝试过:

np.where(np.equal(item from column a, item from column b), 1, 0)

但这不起作用,因为那里有字符串。由于 X 和 Y,我也无法将所有值转换为整数。有什么建议吗?

【问题讨论】:

  • 提供一个代码示例,说明您的数据框的外观或 print(df.head()) 或类似的东西。

标签: python string pandas integer


【解决方案1】:

Pandas 支持类型比较。您可以将pd.Series.__eq__ 用作两个相同类型系列之间的常规比较。

df = pd.DataFrame({'col1': [1, 2, 'hello', 4.5, 'text', 6, 7, 'errr', 9, 'test'],
                   'col2': range(1, 11)})

df['compare'] = (df['col1'] == df['col2']).astype(int)

print(df)

    col1  col2  compare
0      1     1        1
1      2     2        1
2  hello     3        0
3    4.5     4        0
4   text     5        0
5      6     6        1
6      7     7        1
7   errr     8        0
8      9     9        1
9   test    10        0

【讨论】:

  • 这行得通,非常容易理解,谢谢!就我而言,如果值相等,我有一个 if 语句需要运行,例如: if (df['col1'] == df['col2']).astype(int): print('these values are平等的')。这给了我一个attributeErrow:AttributeError:'bool'对象没有属性'astype'。你知道为什么吗?
  • that needs to run if the values are equal。这需要仔细定义。您的意思是如果 所有 值都相等,任何 值都相等,还是要为每一行打印一些值
  • 感谢您的快速响应!假设我想逐行比较两列。例如,如果 col1 row1 == 8 和 col2 row 2 == 8,则 print('这些值相等')。我有一个带有 for 循环的工作代码,但如果其中一项是 int,它会失败。
  • 啊,我明白了,我想这将是一个不同的问题。您介意将其作为一个单独的问题提出吗?在 cmets 中很难编写代码。 (您还可以从其他贡献者那里获得更多选择。)
猜你喜欢
  • 2016-10-16
  • 2020-08-30
  • 2021-11-09
  • 2018-11-07
  • 1970-01-01
  • 2022-11-02
  • 2022-01-22
  • 2013-10-19
  • 1970-01-01
相关资源
最近更新 更多