[英]How to count number of unique strings in two columns?
我有一個包含兩列包含字符串的DataFrame,例如:
col1 --- col2
恩斯特-吉姆
彼得-恩斯特
比爾-NaN
NaN ---道格
吉姆-傑克
現在,我想創建一個新的DataFrame,第一列中包含一個唯一字符串列表,第二列中的兩個原始列中每個字符串的出現次數,例如:
str --- 發生
恩斯特-2
彼得--- 1
比爾--- 1
吉姆-2
傑克--- 1
道格-1
如何以最有效的方式做到這一點? 謝謝!
首先將原始的兩列合並為一個:
In [127]: s = pd.concat([df.col1, df.col2], ignore_index=True)
In [128]: s
Out[128]:
0 Ernst
1 Peter
2 Bill
3 NaN
4 Jim
5 Jim
6 Ernst
7 NaN
8 Doug
9 Jake
dtype: object
然后使用value_counts
:
In [129]: s.value_counts()
Out[129]:
Ernst 2
Jim 2
Bill 1
Doug 1
Jake 1
Peter 1
dtype: int64
我會這樣做(假設您從文件your_file.txt
獲取數據,並且您想打印出結果):
from collections import Counter;
separator = ' --- '
with open('your_file.txt') as f:
content = f.readlines() # here you got a list of elements corresponding to the lines
people = separator.join(content).split(separator) # here you got a list of all elements
people_count = Counter(people) # you got here a dict-like object with key=name value=count
for name, val in people_count.iteritems():
# print the column the way you want
print '{name}{separator}{value}'.format(name=name, separator=separator, value=val)
該示例使用Counter對象,該對象使您可以從可迭代對象中有效地計數元素。 其余代碼僅是字符串操作。
嘗試這個:
df = pd.DataFrame({"col1" : ["Ernst", "Peter","Bill",np.nan,"Jim"],
"col2" : ["Jim","Ernst",np.nan,"Doug","Jake"]})
print df
df1 = df.groupby("col1")["col1"].count()
df2 = df.groupby("col2")["col2"].count()
print df1.add(df2,fill_value=0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.