[英]Count occurrences of number from specific column in python
I am trying to do the equivalent of a COUNTIF() function in excel. 我正在尝试在excel中做一个COUNTIF()函数的等效项。 I am stuck at how to tell the .count() function to read from a specific column in excel.
我坚持如何告诉.count()函数从excel中的特定列读取。
I have 我有
df = pd.read_csv('testdata.csv')
df.count('1')
but this does not work, and even if it did it is not specific enough. 但这是行不通的,即使这样做还不够具体。 I am thinking I may have to use read_csv to read specific columns individually.
我想我可能必须使用read_csv来分别读取特定的列。
Example: 例:
Column name
4
4
3
2
4
1
the function would output that there is one '1' and I could run it again and find out that there are three '4' answers. 该函数将输出一个“ 1”,然后我可以再次运行它,发现存在三个“ 4”的答案。 etc.
等等
I got it to work! 我懂了! Thank you
谢谢
I used: 我用了:
print (df.col.value_counts().loc['x']
If all else fails, why not try something like this? 如果所有其他方法都失败了,为什么不尝试这样的事情呢?
import numpy as np
import pandas
import matplotlib.pyplot as plt
df = pandas.DataFrame(data=np.random.randint(0, 100, size=100), columns=["col1"])
counters = {}
for i in range(len(df)):
if df.iloc[i]["col1"] in counters:
counters[df.iloc[i]["col1"]] += 1
else:
counters[df.iloc[i]["col1"]] = 1
print(counters)
plt.bar(counters.keys(), counters.values())
plt.show()
Here is an example of a simple 'countif' recipe you could try: 这是您可以尝试的简单“计数”配方的示例:
import pandas as pd
def countif(rng, criteria):
return rng.eq(criteria).sum()
df = pd.DataFrame({'column1': [4,4,3,2,4,1],
'column2': [1,2,3,4,5,6]})
countif(df['column1'], 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.