在分析数据时如何处理“比率”值而不使用系列

2024-06-17 10:24:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我的表格中有一列包含“男女比例”,例如:45:55,我想将女性的值(左侧,例如45)放在一列中,男性的值(右侧,例如55)放在一个新的单独列中

我的问题是,我需要在熊猫身上这样做(使用iPython笔记本)。我一直在互联网上搜索一个不使用Series的解决方案——它似乎对我不起作用。有什么建议吗

下面是该列和行的屏幕截图:

Female To Male Ratio Column

任何帮助都将不胜感激


Tags: to屏幕ipython笔记本互联网解决方案建议male
1条回答
网友
1楼 · 发布于 2024-06-17 10:24:08

我相信有一种更优雅的方法可以做到这一点;但是,这里有一个快速而肮脏的选项:

#Create a function to split the values
def splitter(ratio):
    try: #Try to split the values
        return ratio.split(" : ")[0], ratio.split(" : ")[1]
    except AttributeError: #return None for NaN's
        return None, None
#apply the function to the column
df.loc[:, 'MaleNumerator'], df.loc[:, 'FemaleDenominator'] = zip(*df.male_female_Ratio.apply(splitter))

相关问题 更多 >