英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论