Pandas:计算一列中的每个值在另一列中出现的次数

2024-04-19 14:37:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算子列中的值在父列中出现的次数,然后在重命名为子列的新列中显示此计数。请参见下面的预览

我已经通过VBA(COUNTIFS)完成了这项工作,但现在需要动态可视化和动画显示,并使用dir提供的数据。所以我求助于Python和Pandas,在搜索和阅读了如下答案后尝试了以下代码:Countif in pandas with multiple conditionsDetermine if value is in pandas column^ Iterate over rows in Pandas df^许多其他答案。。。 但仍无法获得下图所示的预期预览

任何帮助都将不胜感激。提前谢谢

#import libraries
import pandas as pd
import numpy as np
import os

#get datasets
path_dataset = r'D:\Auto'
df_ns = pd.read_csv(os.path.join(path_dataset, 'Scripts', 'data.csv'), index_col = False, encoding = 'ISO-8859-1', engine = 'python')

#preview dataframe
df_ns

#tried
df_ns.groupby(['Child','Parent', 'Site Name']).size().reset_index(name='child count')

#preview output
df_ns.groupby(['Child','Parent', 'Site Name']).size().reset_index(name='child count')

预览数据帧

enter image description here

预览输出

enter image description here

预期产量

enter image description here

[编辑]我的数据

Child=['Tkt01','Tkt02','Tkt03','Tkt04','Tkt05','Tkt06','Tkt07','Tkt08','Tkt09','Tkt10']

父项=['','Tkt03','','','Tkt03','','','Tkt03','','','Tkt06','','','','',']

场地名称=[Yaounde'、'Douala'、'Bamenda'、'Bafoussam'、'Kumba'、'Garoua'、'Maroua'、'Ngaoundere'、'Buea'、'Ebolowa']


Tags: 数据path答案inimportchildpandasdf
2条回答

由于我无法访问您的数据,因此无法检查我提供给您的代码。我建议您在这一行中使用nan值时遇到问题,但您可以尝试一下:

df_ns['child_count'] = df_ns['Parent'].groupby(df_ns['Child']).value_counts()

我为新列指定了一个名称,并通过groupby->;值计算函数

我创建了一个与您的df相似的外观

以前

enter image description here

试试这个代码

df['Count'] = [len(df[df['parent'].str.contains(value)]) for index, value in enumerate(df['child'])]
#breaking it down as a line by line code

counts = []
for index, value in enumerate(df['child']):
    found = df[df['parent'].str.contains(value)]
    counts.append(len(found))
df['Count'] = counts

之后

enter image description here

希望这对您有用。

相关问题 更多 >