简体   繁体   English

dataframe 列中的不同字符串计数

[英]Distinct string count in dataframe column

I have a.tsv data file.我有一个 .tsv 数据文件。 I want to print the count of strings in a certain column.我想打印某一列中的字符串数。 The column looks like this:该列如下所示:

column1
A aaa
A, C c
C
D
E ee,F
A aaa, B, C cc
F
E ee

I want distinct counts of A,B,C, A aaa etc. But in the column, there are sometimes spaces after the ",".我想要 A、B、C、A aaa 等的不同计数。但是在列中,“,”之后有时会有空格。 So my code counts "B" and " B" differently.所以我的代码对“B”和“B”的计数不同。 This is the code I am currently using:这是我目前使用的代码:

import pandas as pd
import os

# Import data from file into Pandas DataFrame
data= pd.read_csv("data.tsv", encoding='utf-8', delimiter="\t")
pd.set_option('display.max_rows', None)
out = data['Column1'].str.split(',', expand=True).stack().value_counts()
print (out)

Any leads are appreciated.任何线索表示赞赏。

you need to add ' ' into your split, ie split(', ') .您需要将' '添加到您的拆分中,即split(', ') Try ',\s*' for , followed by optional spaces:尝试',\s*' for ,后跟可选空格:

out = df['column1'].str.split(',\s*', expand=True).stack().value_counts()

Output: Output:

F        2
E ee     2
A aaa    2
C c      1
C        1
A        1
C cc     1
B        1
D        1
dtype: int64

Also, you can replace ', ' with ',' and use get_dummies :此外,您可以将', '替换为','并使用get_dummies

df['column1'].str.replace(',\s*',',').str.get_dummies(',').sum()

Output: Output:

A        1
A aaa    2
B        1
C        1
C c      1
C cc     1
D        1
E ee     2
F        2
dtype: int64

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM