【问题标题】:Processing multiple values string in Pandas DataFrame column在 Pandas DataFrame 列中处理多个值字符串
【发布时间】: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']

这似乎不起作用。

谢谢。

【问题讨论】:

  • 您能否添加代码以生成与您正在使用的框架相似的框架,或者显示这样的框架并使用示例框架重新表述您的问题?

标签: python pandas


【解决方案1】:

这是你打算做的吗?

for i in range(1,6):
    df['super_'+str(i)] = df['place'].map(lambda x: x.count(str(i)) )

【讨论】:

    猜你喜欢
    • 2018-03-16
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 2022-12-29
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    相关资源
    最近更新 更多