我正在嘗試編寫一個函數,該函數從我之前在代碼中定義的pandas DataFrame中調用特定列。我如何定義一個調用python中特定數據框列的函數/宏?
數據幀可以是簡單的東西,比如
df = pd.DataFrame(
{
'col0': np.random.randint(0,100,100),
'col1': np.random.randint(0,100,100),
'col2': np.random.randint(0,100,100)
}
)
下一個步驟將是編寫調用COL0,COL1,COL2或功能。
def hist(x):
return np.histogram(
df['x'],
bins = 6
)
但是,當您通過在數據幀中定義的列名調用函數,Python不認識的名字;
In [1]: hist(col1)
Traceback (most recent call last):
File "<ipython-input-68-e860df6abc8e>", line 1, in <module>
hist(col1)
NameError: name 'col1' is not defined
是否有解決此問題的方法?
您已經GIOT混了變量名的字符串。 'df ['x']'必須是'df [x]',並且函數調用中的'col1'必須是'「col1」'。 – DyZ