我试图找到某个值出现在一列中的次数.
我已经制作了数据帧 data = pd.DataFrame.from_csv('data/DataSet2.csv')
现在我想找到某个列出现的次数.这是怎么做到的?
我认为这是下面的,我正在查看教育专栏并计算?发生的时间.
下面的代码显示我试图找到9th出现的次数,错误是我运行代码时得到的
码
missing2 = df.education.value_counts()['9th']
print(missing2)
Run Code Online (Sandbox Code Playgroud)
错误
KeyError: '9th'
Run Code Online (Sandbox Code Playgroud)
jez*_*ael 44
您可以subset根据自己的条件创建数据,然后使用shape或len:
print df
col1 education
0 a 9th
1 b 9th
2 c 8th
print df.education == '9th'
0 True
1 True
2 False
Name: education, dtype: bool
print df[df.education == '9th']
col1 education
0 a 9th
1 b 9th
print df[df.education == '9th'].shape[0]
2
print len(df[df['education'] == '9th'])
2
Run Code Online (Sandbox Code Playgroud)
性能很有趣,最快的解决方案是比较numpy数组和sum:
代码:
import perfplot, string
np.random.seed(123)
def shape(df):
return df[df.education == 'a'].shape[0]
def len_df(df):
return len(df[df['education'] == 'a'])
def query_count(df):
return df.query('education == "a"').education.count()
def sum_mask(df):
return (df.education == 'a').sum()
def sum_mask_numpy(df):
return (df.education.values == 'a').sum()
def make_df(n):
L = list(string.ascii_letters)
df = pd.DataFrame(np.random.choice(L, size=n), columns=['education'])
return df
perfplot.show(
setup=make_df,
kernels=[shape, len_df, query_count, sum_mask, sum_mask_numpy],
n_range=[2**k for k in range(2, 25)],
logx=True,
logy=True,
equality_check=False,
xlabel='len(df)')
Run Code Online (Sandbox Code Playgroud)
小智 14
尝试这个:
(df[education]=='9th').sum()
Run Code Online (Sandbox Code Playgroud)
Zer*_*ero 13
几种方式使用count或sum
In [338]: df
Out[338]:
col1 education
0 a 9th
1 b 9th
2 c 8th
In [335]: df.loc[df.education == '9th', 'education'].count()
Out[335]: 2
In [336]: (df.education == '9th').sum()
Out[336]: 2
In [337]: df.query('education == "9th"').education.count()
Out[337]: 2
Run Code Online (Sandbox Code Playgroud)
计算 Pandas 数据框中列中出现次数(唯一值)的简单示例:
import pandas as pd
# URL to .csv file
data_url = 'https://yoursite.com/Arrests.csv'
# Reading the data
df = pd.read_csv(data_url, index_col=0)
# pandas count distinct values in column
df['education'].value_counts()
Run Code Online (Sandbox Code Playgroud)
输出:
Education 47516
9th 41164
8th 25510
7th 25198
6th 25047
...
3rd 2
2nd 2
1st 2
Name: name, Length: 190, dtype: int64
Run Code Online (Sandbox Code Playgroud)
小智 5
计算'?'任何列中任何符号或任何符号的出现的一种优雅方法是使用isin数据框对象的内置函数。
假设我们已将“汽车” 数据集加载到df对象中。我们不知道哪些列包含缺失值('?'符号),所以请执行以下操作:
df.isin(['?']).sum(axis=0)
Run Code Online (Sandbox Code Playgroud)
DataFrame.isin(values) 官方文件说:
它返回布尔型DataFrame,显示该DataFrame中的每个元素是否包含在值中
注意,它isin接受一个iterable作为输入,因此我们需要将包含目标符号的列表传递给此函数。df.isin(['?'])将返回一个布尔数据框,如下所示。
symboling normalized-losses make fuel-type aspiration-ratio ...
0 False True False False False
1 False True False False False
2 False True False False False
3 False False False False False
4 False False False False False
5 False True False False False
...
Run Code Online (Sandbox Code Playgroud)
要计算目标符号在每一列中的出现次数,我们sum通过指示来接管上述数据框的所有行axis=0。最终(截断)结果显示了我们的期望:
symboling 0
normalized-losses 41
...
bore 4
stroke 4
compression-ratio 0
horsepower 2
peak-rpm 2
city-mpg 0
highway-mpg 0
price 4
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75240 次 |
| 最近记录: |