检查列是否具有相同的字符串

huangapple go评论56阅读模式
英文:

check column has the same string

问题

I would like to check if a dataframe column has the same string.
for example, below dataframe in columns AAA, I want to check if all string is Jack, so the function call should return true!

import pandas as pd

data = {
    'AAA' :
    ['Jack','Jack','Jack','Jack','Jack'],
    'BBB' :
    ['January', 'February', 'February', 'April', 'January'],
    'CCC' :
    [85, 96, 55, 64,60]
}

df = pd.DataFrame(data)

print(len(df['AAA'].unique()) == 1)

unique can be used to check value is the same, but I need to check the string is Jack as well.

英文:

I would like to check if a dataframe column has the same string.
for example, below dataframe in columns AAA, I want to check if all string is Jack, so the function call should return true!

import pandas as pd

data = {
    'AAA' :
    ['Jack','Jack','Jack','Jack','Jack'],
    'BBB' :
    ['January', 'February', 'February', 'April', 'January'],
    'CCC' :
    [85, 96, 55, 64,60]
}

df = pd.DataFrame(data)

print(len(df['AAA'].unique()) == 1)

unique can be used to check value is the same, but I need to check the string is Jack as well.

答案1

得分: 1

以下是翻译好的部分:

data = {
    'AAA':
    ['Jack', 'Jack', 'Jack', 'Jack', 'Jack'],
    'BBB':
    ['January', 'February', 'February', 'April', 'January'],
    'CCC':
    [85, 96, 55, 64, 60]
}

df = pd.DataFrame(data)

is_all_jack = len(df['AAA'].unique()) == 1 and df['AAA'].unique()[0] == 'Jack'
print(is_all_jack)
英文:

You can use the following modification:

data = {
    'AAA' :
    ['Jack','Jack','Jack','Jack','Jack'],
    'BBB' :
    ['January', 'February', 'February', 'April', 'January'],
    'CCC' :
    [85, 96, 55, 64,60]
}

df = pd.DataFrame(data)

is_all_jack = len(df['AAA'].unique()) == 1 and df['AAA'].unique()[0] == 'Jack'
print(is_all_jack)

答案2

得分: 0

尝试使用 value_counts 函数:

df['AAA'].value_counts()
英文:

try value_counts

df['AAA'].value_counts()

答案3

得分: 0

Output: True

英文:
import pandas as pd

data = {
    'AAA': ['Jack', 'Jack', 'Jack', 'Jack', 'Jack'],
    'BBB': ['January', 'February', 'February', 'April', 'January'],
    'CCC': [85, 96, 55, 64, 60]
}

df = pd.DataFrame(data)

is_same_string = (df['AAA'] == 'Jack').all()

print(is_same_string)

Output: True

huangapple
  • 本文由 发表于 2023年6月6日 04:19:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76409740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定