Python数据框: Remove digits in odd position from df rows?

标签 python pandas numpy dataframe

我有一个包含两列 numbertype 的 df。如果 typeodd,我会尝试删除奇数位置的数字。

对于数字 - (7,14,21,28),在奇数位置没有数字 - 7,21

同样 - (3,10,17,24,31)奇数位置没有数字 - 3,17,31

df

    df= pd.DataFrame(data = {'number' : ['7,14,21,28', '2', '3,6,5,8 ', '4', '3,10,17,24,31'], 'day' : ['odd', 'even', 'even', 'even', 'odd']}) 


    number          type
0   7,14,21,28      odd
1   2               even   
2   3,6,5,8         even
3   4               even
4   3,10,17,24,31   odd

我的异常输出:

        number          type
    0   7,21            odd
    1   2               even   
    2   3,6,5,8         even
    3   4               even
    4   3,17,31         odd

最佳答案

您可以使用简单的string slicing步骤= 2:

In [1755]: df.number = np.where(df['day'].eq('odd'), df.number.str.split(',').str[::2].str.join(','), df['number'])

In [1759]: df                                              
Out[1759]: 
     number   day
0      7,21   odd
1         2   even
2   3,6,5,8   even
3         4   even
4   3,17,31   odd

关于Python数据框: Remove digits in odd position from df rows?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62007888/

相关文章:

python - 以图像作为标签的 Caffe 测试网

python - 如何有效地向量化超几何 CDF 计算?

numpy - numpy pypi 包命名约定是什么

python - 让本地 numpy 覆盖全局

python - 可以将 pandas DataFrame 保存为 "append mode"中的二进制文件吗?

python - Python 并安装 mysql 连接器

python - 运行用户数据脚本 AWS EC2 时出现问题

python - Pandas 导入 : ModuleNotFoundError: No module named 'pandas._libs.tslib'

python - 简化pan​​das表达式

python - 使用 pandas 确定上个月的客户本月是否有销售额