首页 > 解决方案 > Pandas:如何在 pandas 数据框中的列上使用 map 来创建新列?使用 lambda 函数执行此操作时遇到问题

问题描述

我有一个数据集,其中包含 1 列中的字符串,我想计算最常见的字符并将该字符放入新列中。我还想要另一列包含字符所代表的字符串的比例。

我想在每个字符串上使用的方法如下:

sequence = 'ACCCCTGGC'
char_i_want = collections.Counter(sequence).most_common(1)[0] # for the character
value_i_want = collections.Counter(sequence).most_common(1)[1] / len(sequence) # for the proportion

我知道 most_common 的结果是一个元组,但是当我在 python shell 中尝试这个时,我需要collections.Counter(sequence).most_common(1)[0][0]访问元组的第 0 个元素,元组是返回列表的第 0 个元素。当我尝试实现它时,它仍然没有用。

这是我尝试这样做的方法:

def common_char(sequence):
    return Counter(sequence).most_common(1)[0][0]

def char_freq(sequence):
    return Counter(sequence).most_common(1)[0][1] / len(sequence)

data = pd.read_csv('final_file_noidx.csv')
data['most_common_ref'] = data['REF'].map(lambda x: common_char(x))
data['most_common_ref_frac'] = data['REF'].map(lambda x: char_freq(x))

我收到此错误消息:TypeError: 'float' object is not iterable

标签: pythonpandasdictionarycollectionscounter

解决方案


data['most_common_ref'] = data['REF'].map(lambda x: common_char(x), na_action='ignore')
data['most_common_ref_frac'] = data['REF'].map(lambda x: char_freq(x), na_action='ignore')

需要忽略 NaN,感谢 Andy L。


推荐阅读