我有一個像
animal, small_animal, count
cat, dog, 1
cat, moo, 2
dog, cat, 3
moo, moo, 5
squirrel, moo, 1
moo, cat, 3
我想一起儲存
cat, dog和dog, cat
所以我需要檢查列中是否同時出現但以不同的“順序”出現,并保留第三列。我想到了多個不同的資料框或字典。到目前為止,我做了一個groupby,但我仍然無法解決其他問題。
uj5u.com熱心網友回復:
您可以使用標簽創建一個新列
df["label_col"] = df[["animal", "small_animal"]].apply(
lambda x: "-".join(sorted(x)), axis=1
)
"""
Output
animal small_animal count label_col
0 cat dog 1 cat-dog
1 cat moo 2 cat-moo
2 dog cat 3 cat-dog
3 moo moo 5 moo-moo
4 squirrel moo 1 moo-squirrel
5 moo cat 3 cat-moo
"""
然后你可以按順序分組或做任何你想做的事情label_col
uj5u.com熱心網友回復:
您可以嘗試比較以不同順序連接的兩列,并在兩列中過濾掉相同的動物。
m = (df['animal'] df['small_animal']).isin(df['small_animal'] df['animal'])
out = df[m & df['animal'].ne(df['small_animal'])]
print(out)
animal small_animal count
0 cat dog 1
1 cat moo 2
2 dog cat 3
5 moo cat 3
uj5u.com熱心網友回復:
以反射形式出現的具有不同名稱的記錄
names = ['animal', 'small_animal']
# include all pairs of animal names which occur in reflected form
is_reflected = pd.Index(df[names]).isin(pd.Index(df[reversed(names)]))
# exclude records where names are duplicated, sort of ('moo', 'moo') pairs
is_different = df.animal != df.small_animal
# extract counts for records with reflected and different names
df[is_reflected & is_different]['count']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/475765.html
標籤:Python python-3.x 熊猫 数据框 字典
上一篇:如何從字典中獲取元素
下一篇:如何計算地圖中的字串?
