【发布时间】:2018-02-27 19:24:13
【问题描述】:
我想向这个 DataFrame 添加总字段:
df_test = pd.DataFrame([
{'id':1,'cat1a':3,'cat1b':2, 'cat2a':4,'cat2b':3},
{'id':2,'cat1a':7,'cat1b':5, 'cat2a':9,'cat2b':6}
])
这段代码几乎可以工作:
def add_total(therecord):
t1 = therecord['cat1a'] + therecord['cat1b']
t2 = therecord['cat2a'] + therecord['cat2b']
return t1, t2
df_test['cat1tot', 'cat2tot'] = df_test[['cat1a', 'cat1b', 'cat2a', 'cat2b']].apply(add_total,axis=1)
除非它只产生 1 个新列:
还有这段代码:
def add_total(therecord):
t1 = therecord['cat1a'] + therecord['cat1b']
t2 = therecord['cat2a'] + therecord['cat2b']
return [t1, t2]
df_test[['cat1tot', 'cat2tot']] = df_test[['cat1a', 'cat1b', 'cat2a', 'cat2b']].apply(add_total,axis=1)
结果:KeyError: "['cat1tot' 'cat2tot'] not in index"
我试图解决这个问题:
my_cols_list=['cat1tot','cat2tot']
df_test.reindex(columns=[*df_test.columns.tolist(), *my_cols_list], fill_value=0)
但这并没有解决问题。那我错过了什么?
【问题讨论】:
-
您是否尝试过
.withColumn(),可能使用.drop()来删除不需要的源列?还是df_test.select((df_test.cat1a + df_test.cat1b).alias("cat1tot"))等? -
@9000 这些对我来说看起来不像是有效的 pandas 函数......你运行的是什么版本?
-
@BradRhoads,您是否只想添加无法矢量化的总数或更复杂的计算?
-
@cᴏʟᴅsᴘᴇᴇᴅ:啊,把 Pandas
DataFrame误认为 SparkDataFrame!因此混乱。确实,这不适用于 Pandas。