[英]Count distinct values for each column, return a dataframe, and sort values
This is my code: 这是我的代码:
for column in list(data.columns):
pd.DataFrame(columns=column, data=data.columns.nunique()).sort_values()
This doesn't work...... 这行不通......
Either to define a function or use a for loop, how can I make it simple to check the unique value number of each column? 定义函数还是使用for循环,如何使检查每一列的唯一值编号变得简单?
There are many issues with your code, but the two main ones: 您的代码有很多问题,但有两个主要问题:
pd.DataFrame
objects you create. pd.DataFrame
对象添加到列表中。 nunique
to column labels, not to the data within your dataframe. nunique
应用于列标签,而不是数据nunique
的数据。 Here you can use nunique
directly with your dataframe, then sort_values
: 在这里,您可以直接在数据
nunique
使用nunique
,然后再使用sort_values
:
np.random.seed(0)
df = pd.DataFrame(np.random.randint(0, 10, (5, 5)))
res = df.nunique()\
.sort_values(ascending=False)\
.rename('Count')\
.to_frame()
print(res)
Count
1 5
3 4
2 4
0 4
4 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.