PythonPandas:一个系列中有多少个值在另一个系列中?

2024-03-28 12:47:51 发布

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

我有两个数据帧:

df1 = pd.DataFrame(
    {
    "col1": ["1","2",np.nan,"3"],
    }
)

df2 = pd.DataFrame(
    {
    "col1": [2.0,3.0,4.0,np.nan],
    }
)

我想知道在df2.col1中有多少df1.col1的值。在本例中,它应该是2,因为我希望"2"2.0被视为相等。你知道吗

我确实有一个可行的解决方案,但因为我认为我会更经常地需要这个(当然,出于学习的目的),我想问你,是否有一个更舒适的方法来做到这一点。你知道吗

df1.col1[df1.col1.notnull()].isin(df2.col1[df2.col1.notnull()].astype(int).astype(str)).value_counts()

enter image description here


Tags: 数据方法目的dataframenpnan解决方案col1
1条回答
网友
1楼 · 发布于 2024-03-28 12:47:51

如果使用integers和缺少的值,请使用^{}并转换为浮点:

a = df1.col1.dropna().astype(float).isin(df2.col1.dropna()).value_counts()

或:

a = df1.col1.dropna().isin(df2.col1.dropna().astype(int).astype(str)).value_counts()

相关问题 更多 >