2024-04-23 22:47:33 发布
网友
我正在尝试获取多列中的第一个元素,并计算该值出现的次数。你知道吗
A B 1,2,3 23,4,5 2 54 2 2
result 1 1 2 3 54 1 32 1
对Series使用^{},然后^{}通过索引选择第一个值,必要时转换为整数并按^{}计数,必要时最后排序:
Series
s = df.stack().str.split(',').str[0].astype(int).value_counts().sort_index() print (s) 1 1 2 3 23 1 54 1 dtype: int64
如果需要2列数据帧:
df1 = (df.stack() .str.split(',') .str[0] .astype(int) .value_counts() .sort_index() .rename_axis('result') .reset_index(name='counts')) print (df1) result counts 0 1 1 1 2 3 2 23 1 3 54 1
对} ,然后^{} 通过索引选择第一个值,必要时转换为整数并按^{} 计数,必要时最后排序:
Series
使用^{如果需要2列数据帧:
相关问题 更多 >
编程相关推荐