【问题标题】:How do I check if all values in a column of a pandas dataframe are equal?如何检查熊猫数据框列中的所有值是否相等?
【发布时间】:2020-03-18 12:04:08
【问题描述】:

我有一个这样的数据框

  name data result 
0  x    100
1  x    100
2  x    100
3  x    100
4  x    100
5  y    100
6  y    90
7  y    90
8  y    100
9  y    85

我想检查name 列中的每个组在data 列中是否具有相同的值。

所以对于每个x 组,如果对应的data 值都相等,则在result 列中写入full。如果一个组的值不相等,请在result 列中写入nearly。

我已尝试对数据框进行分组:

dfx = df.groupby('name')
dfx = dfa.get_group('x')

但它并不能真正帮助检查每个值是否相同,请写入result 列。

我尝试创建一个检查唯一值的函数

def check_identicals(row):
    if(df.sent.nunique() == 1):
        print('Full')

这里的想法是将该函数应用于每一行并将输出写入result 列。

理想输出:

   name data result 
0  x    100   full
1  x    100   full
2  x    100   full
3  x    100   full
4  x    100   full
5  y    100   nearly
6  y    90    nearly
7  y    90    nearly
8  y    100   nearly
9  y    85    nearly

【问题讨论】:

标签: python pandas dataframe apply


【解决方案1】:

使用numpy.where 与GroupBy.transform 和DataFrameGroupBy.nunique 比较新Series 中的所有值与原始DataFrame 相同大小:

df['result'] = np.where(df.groupby('name')['data'].transform('nunique') == 1,'full','nearly')
print (df)
  name  data  result
0    x   100    full
1    x   100    full
2    x   100    full
3    x   100    full
4    x   100    full
5    y   100  nearly
6    y    90  nearly
7    y    90  nearly
8    y   100  nearly
9    y    85  nearly

编辑:

为了测试每组的所有缺失值是否使用numpy.select 和另一个条件,将缺失值与transform 和GroupBy.all 进行比较:

m1 = df.groupby('name')['data'].transform('nunique') == 1
m2 = df['data'].isna().groupby(df['name']).transform('all')

df['result'] = np.select([m1, m2], ['full', 'all_missing'],'nearly')
print (df)
  name   data       result
0    x  100.0         full
1    x  100.0         full
2    x  100.0         full
3    x  100.0         full
4    x  100.0         full
5    y  100.0       nearly
6    y   90.0       nearly
7    y   90.0       nearly
8    z    NaN  all_missing
9    z    NaN  all_missing

【讨论】:

  • 有没有办法包含 isnull() 条件?假设不同组的每个数据值是否为 Null,请在结果列中指出?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 2019-06-21
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多