假设我有一个df列'ID', 'col_1', 'col_2'.我定义了一个函数:
f = lambda x, y : my_function_expression.
现在我想应用fto df的两列'col_1', 'col_2'来逐元素地计算一个新列'col_3',有点像:
df['col_3'] = df[['col_1','col_2']].apply(f)
# Pandas gives : TypeError: ('<lambda>() takes exactly 2 arguments (1 given)'
Run Code Online (Sandbox Code Playgroud)
怎么做 ?
** 添加详细示例如下 ***
import pandas as pd
df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']
def get_sublist(sta,end):
return mylist[sta:end+1]
#df['col_3'] = df[['col_1','col_2']].apply(get_sublist,axis=1)
# expect above to output df as below
ID col_1 col_2 col_3
0 1 0 …Run Code Online (Sandbox Code Playgroud) 我试图根据帖子的文本和其他功能(一天中的时间,帖子的长度等)来模拟帖子收到的分数.
我想知道如何最好地将这些不同类型的功能组合到一个模型中.现在,我有类似以下内容(从这里和这里被盗).
import pandas as pd
...
def features(p):
terms = vectorizer(p[0])
d = {'feature_1': p[1], 'feature_2': p[2]}
for t in terms:
d[t] = d.get(t, 0) + 1
return d
posts = pd.read_csv('path/to/csv')
# Create vectorizer for function to use
vectorizer = CountVectorizer(binary=True, ngram_range=(1, 2)).build_tokenizer()
y = posts["score"].values.astype(np.float32)
vect = DictVectorizer()
# This is the part I want to fix
temp = zip(list(posts.message), list(posts.feature_1), list(posts.feature_2))
tokenized = map(lambda x: features(x), temp)
X = vect.fit_transform(tokenized)
Run Code Online (Sandbox Code Playgroud)
从pandas数据框中提取我想要的所有功能似乎非常愚蠢,只是将它们全部压缩在一起.有没有更好的方法来做这一步?
CSV看起来如下所示: …