简体   繁体   English

Pandas dataframe - 检查多行是否具有相同的值

[英]Pandas dataframe - check if multiple rows have the same value

I have a DataFrame which looks like this:我有一个 DataFrame,它看起来像这样:

Reference参考 Value价值
String1字符串 1 1 1个
String2字符串 2 0 0
String3字符串 3 -1 -1
String2字符串 2 1 1个
String1字符串 1 1 1个
String3字符串 3 0 0

Each reference can appear in the dataframe either once, two times, or three times;每个引用可以在 dataframe 中出现一次、两次或三次; and can have either the same or different value associated.并且可以关联相同或不同的值。 I would like to create another dataframe which tells me, for each Reference, do they all have the same value or not.我想创建另一个 dataframe,它告诉我,对于每个参考,它们是否都具有相同的值。 So with the example above, I would like to get something like this:所以对于上面的例子,我想得到这样的东西:

Reference参考 Value价值
String1字符串 1 Yes是的
String2字符串 2 No
String3字符串 3 No

(I put Yes and No as an example but it could be 1/0 or whatever else) (我以是和否为例,但它可以是 1/0 或其他任何东西)

How can I do this?我怎样才能做到这一点?

My initial thought was to use a .groupby but then I didn't find any type of aggregation which would help me here...我最初的想法是使用.groupby但后来我没有找到任何类型的聚合可以帮助我......

You could use groupby + nunique to get a count of unique Values for each Reference.您可以使用groupby + nunique来计算每个引用的唯一值。 Then use np.where to assign Yes/No values depending on if the number of unique values is 1 or not:然后使用np.where根据唯一值的数量是否为 1 来分配是/否值:

out = df.groupby('Reference', as_index=False)['Value'].nunique()
out['Value'] = np.where(out['Value'].eq(1), 'Yes', 'No')

Output: Output:

  Reference Value
0   String1   Yes
1   String2    No
2   String3    No

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将行附加到 Pandas 数据帧,并将多个重叠单元格(具有相同索引)转换为单个值,而不是一个系列? - How to append rows to a Pandas dataframe, and have it turn multiple overlapping cells (with the same index) into a single value, instead of a series? 对熊猫数据框的行进行操作,其中列的值相同 - operations on rows of a pandas dataframe which columns have the same value 在熊猫数据框中添加具有相同列值的行 - Adding rows that have the same column value in a pandas dataframe 如何组合 pandas dataframe 中在一列中具有相同值的行 - How to combine rows in a pandas dataframe that have the same value in one column pandas 如何检查以下两行是否具有相同的列值 - pandas how to check if the following 2 rows have the same column value 如何检查 pandas 列中接下来的 3 个连续行是否具有相同的值? - How to check if next 3 consecutive rows in pandas column have same value? 计算多列中具有相同字符串值的pandas数据框中的总行 - counting total rows in pandas dataframe with the same string value in multiple columns Python Pandas:在具有相同索引的多行中检查列的值 - Python Pandas: Check the value of a column over multiple rows with the same index Pandas - 合并具有共享值的 dataframe 行 - Pandas - Merge rows of dataframe that have a shared value Pandas Dataframe 具有相同索引的多行 - Pandas Dataframe multiple rows with same index
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM