[英]Python - how to pass a dynamic Series name and DataFrame name as a function argument?
我想編寫一個函數,該函數接收熊貓數據框和給定的序列名稱,並檢索該序列的唯一值及其在數據集中的頻率。
def getUniqueValuesByField(dataframe, fieldname):
''' Retrive for non-numerical series the unique values and their frequencies '''
result = dataframe.fieldname.apply(lambda x: pd.Series(x)).unstack().value_counts(normalize=True, sort=True, ascending=False, bins=None, dropna=True)
#dataframe[fieldname].unique()
return result
然后,我可以按以下方式調用此函數:
df = pd.DataFrame.from_dict(RequestsDict)
getUniqueValuesByField(df, 'detected_language')
getUniqueValuesByField(df, 'detected_vertical')
可能嗎? 我試圖連接字符串並使用eval()函數,但是我不確定這是否是正確的方法。
使用.value_counts()
就像這樣:
In [35]: df = pd.DataFrame(['foo','bar','baz', 'foo','bar'], columns=['test'])
In [36]: df['test'].value_counts()
Out[36]:
foo 2
bar 2
baz 1
dtype: int64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.