【发布时间】:2012-08-20 02:25:49
【问题描述】:
我有一个问卷数据集,其中一列(一个问题)有多个可能的答案。该列的数据是一个列表,有多个可能的值,从无到五个,即'[1]' 或'[1, 2, 3, 5]'
我正在尝试处理该列以独立访问值,如下所示:
def f(x):
if notnull(x):
p = re.compile( '[\[\]\'\s]' )
places = p.sub( '', x ).split( ',' )
place_tally = {'1':0, '2':0, '3':0, '4':0, '5':0}
for place in places:
place_tally[place] += 1
return place_tally
df['places'] = df.where_buy.map(f)
这会在我的数据框“places”中创建一个新列,其中包含来自值的字典,即:{'1': 1, '3': 0, '2': 0, '5': 0, '4': 0} 或 {'1': 1, '3': 1, '2': 1, '5': 1, '4': 0}
现在从新列中提取数据的最有效/最简洁的方法是什么?我试过遍历 DataFrame 没有好的结果,即
for row_index, row in df.iterrows():
r = row['places']
if r is not None:
df.ix[row_index]['large_super'] = r['1']
df.ix[row_index]['small_super'] = r['2']
这似乎不起作用。
谢谢。
【问题讨论】:
-
您能否添加代码以生成与您正在使用的框架相似的框架,或者显示这样的框架并使用示例框架重新表述您的问题?