क्या उन आईडी को खोजने का कोई तरीका है जिनमें ऐप्पल और स्ट्रॉबेरी दोनों हैं, और फिर कुल लंबाई पाएं? और आईडी जिनमें केवल ऐप्पल है, और आईडीएस जिसमें केवल स्ट्रॉबेरी है?
डीएफ:
ID Fruit
0 ABC Apple <-ABC has Apple and Strawberry
1 ABC Strawberry <-ABC has Apple and Strawberry
2 EFG Apple <-EFG has Apple only
3 XYZ Apple <-XYZ has Apple and Strawberry
4 XYZ Strawberry <-XYZ has Apple and Strawberry
5 CDF Strawberry <-CDF has Strawberry
6 AAA Apple <-AAA has Apple only
वांछित आउटपुट:
Length of IDs that has Apple and Strawberry: 2
Length of IDs that has Apple only: 2
Length of IDs that has Strawberry: 1
धन्यवाद!
2 जवाब
यदि हमेशा सभी मान केवल Apple
या Strawberry
कॉलम Fruit
में हैं, तो आप प्रति समूह सेट की तुलना कर सकते हैं और फिर ID
को True
के sum
से गिन सकते हैं। एस मान:
v = ['Apple','Strawberry']
out = df.groupby('ID')['Fruit'].apply(lambda x: set(x) == set(v)).sum()
print (out)
2
संपादित करें: यदि कई मान हैं:
s = df.groupby('ID')['Fruit'].agg(frozenset).value_counts()
print (s)
{Apple} 2
{Strawberry, Apple} 2
{Strawberry} 1
Name: Fruit, dtype: int64
आप डेटाफ़्रेम के लिए pivot_table
और value_counts
का उपयोग कर सकते हैं (पंडों 1.1.0.):
df.pivot_table(index='ID', columns='Fruit', aggfunc='size', fill_value=0)\
.value_counts()
आउटपुट:
Apple Strawberry
1 1 2
0 2
0 1 1
वैकल्पिक रूप से आप इसका उपयोग कर सकते हैं:
df.groupby(['ID', 'Fruit']).size().unstack('Fruit', fill_value=0)\
.value_counts()
संबंधित सवाल
जुड़े हुए प्रश्न
नए सवाल
python-3.x
पायथन प्रोग्रामिंग के बारे में प्रश्नों के लिए जो भाषा के संस्करण 3+ के लिए विशिष्ट हैं। सभी पायथन सवालों पर अधिक जेनेरिक [अजगर] टैग का उपयोग करें, और केवल यह जोड़ें यदि आपका प्रश्न संस्करण-विशिष्ट है। पायथन 2 प्रश्नों के लिए [अजगर -2] टैग का उपयोग करें।