簡體   English   中英

Python:在DataFrame中,如何遍歷一列的所有字符串並檢查它們是否出現在另一列中並計數?

[英]Python: In a DataFrame, how do I loop through all strings of one column and check to see if they appear in another column and count them?

我有一個數據框,想要遍歷c2列中的所有單元格,並計算每個完整字符串出現在另一列c1 (如果存在)的次數。 然后打印結果。

df示例:

id     c1                c2
0      luke skywalker    han solo
1      leia organa       r2d2
2      darth vader       finn
3      han solo          the emporer
4      han solo          c3po
5      finn              leia organa
6      r2d2              darth vader

示例打印結果:

han solo      2
r2d2          1
finn          1
the emporer   0
c3po          0
leia organa   1
darth vader   1

我正在將Jupyter Notebook與python和pandas一起使用。 謝謝!

您可以使用一些Numpy魔術。
使用count和廣播比較每個組合。

from numpy.core.defchararray import count

c1 = df.c1.values.astype(str)
c2 = df.c2.values.astype(str)

pd.Series(
    count(c1, c2[:, None]).sum(1),
    c2
)

han solo       2
r2d2           1
finn           1
the emporer    0
c3po           0
leia organa    1
darth vader    1
dtype: int64

您可以將它們作為category並使用value_counts傳遞

df.c1.astype('category',categories=df.c2.tolist()).value_counts(sort=False)
Out[572]: 
han solo       2
r2d2           1
finn           1
the emporer    0
c3po           0
leia organa    1
darth vader    1
Name: c1, dtype: int64

或者你可以做

pd.crosstab(df.c2,df.c1).sum().reindex(df.c2,fill_value=0)
Out[592]: 
c2
han solo       2
r2d2           1
finn           1
the emporer    0
c3po           0
leia organa    1
darth vader    1
df[c3] = pd.Series([df[c1].count(n) for n in df[c2]])

暫無
暫無

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

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