python - 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
解决方案
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。
推荐阅读
- macos - 创建启动另一个应用程序的缩放(Mac 桌面)插件
- python - 使用 python/pandas 将唯一值与特定列及其字段匹配
- css - 顺风对齐项目
- javascript - 角度嵌套模块未加载嵌套路由器出口
- r - 在for循环内计数nrow的R问题
- python - ruamel.yaml:将注释固定到下一个数据项而不是前一个
- reactjs - 重新选择的createSelector:它是否对嵌套对象进行深度比较?
- pandas - 试图从 nbcsport 获取玩家数据
- c# - 如何在 24 小时内将数据表永久保存在“缓存”中?
- python - 解析从 Latex 到 sympy 的实数集