簡體   English   中英

列表相對於Pandas數據框中每一行的出現頻率

[英]Occurence frequency from a list against each row in Pandas dataframe

假設我有一個名為“ base”的6個整數的列表,還有一個包含100,000行和6列整數的數據框。

我需要創建一個額外的列,該列針對數據幀數據中的每一行顯示列表“ base”的出現頻率。

在這種情況下,列表“ base”和數據幀中的整數序列都將被忽略。

發生頻率的取值范圍為0到6。
0表示列表'base'中的所有6個整數與數據幀中一行的6列都不匹配。

任何人都可以對此有所了解嗎?

您可以嘗試以下方法:

import pandas as pd

# create frame with six columns of ints
df = pd.DataFrame({'a':[1,2,3,4,10],
                   'b':[8,5,3,2,11],
                   'c':[3,7,1,8,8],
                   'd':[3,7,1,8,8],
                   'e':[3,1,1,8,8],
                   'f':[7,7,1,8,8]})

# list of ints
base =[1,2,3,4,5,6]

# define function to count membership of list
def base_count(y):
    return sum(True for x in y if x in base)

# apply the function row wise using the axis =1 parameter
df.apply(base_count, axis=1)

輸出:

0    4
1    3
2    6
3    2
4    0
dtype: int64

然后將其分配給新列:

df['g'] = df.apply(base_count, axis=1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM