BC *_*ith 5 text-extraction dataframe python-3.x pandas data-science
我试图在两个不同的数据框中仅提取数字和字符串。我正在使用正则表达式来提取数字和字符串。
\nimport pandas as pd\n\ndf_num = pd.DataFrame({\n \'Colors\': [\'lila1.5\', \'rosa2.5\', \'gelb3.5\', \'gr\xc3\xbcn4\', \'rot5\', \'schwarz6\', \'grau7\', \'wei\xc3\x9f8\', \'braun9\', \'hellblau10\'],\n \'Animals\': [\'hu11nd\', \'12welpe\', \'13katze\', \'s14chlange\', \'vo15gel\', \'16papagei\', \'ku17h\', \'18ziege\', \'19pferd\',\n \'esel20\']\n })\n\nfor column in df_num.columns:\n df_num[column] = df_num[column].str.extract(\'(\\d+)\').astype(float)\n\nprint(df_num)\nRun Code Online (Sandbox Code Playgroud)\n我也尝试过使用\'([\\d+][\\d+\\.\\d+])\' and \'([\\d+\\.\\d+])\'
在这里我得到了输出,但不是我所期望的。虽然我期待浮点数,但我没有得到 1.5 或 2.5。
\n我得到如下图所示的内容:
\n\ndf_str = pd.DataFrame({\n \'Colors\': [\'lila1.5\', \'rosa2.5\', \'gelb3\', \'gr\xc3\xbcn4\', \'rot5\', \'schwarz6\', \'grau7\', \'wei\xc3\x9f8\', \'braun9\', \'hellblau10\'],\n \'Animals\': [\'hu11nd\', \'12welpe\', \'13katze\', \'s14chlange\', \'vo15gel\', \'16papagei\', \'ku17h\', \'18ziege\', \'19pferd\',\n \'esel20\']\n })\n\nfor column in df_str.columns:\n df_str[column] = df_str[column].str.extract(\'([a-zA-Z]+)\')\n\nprint(df_str)\nRun Code Online (Sandbox Code Playgroud)\n在这种情况下,当数字位于末尾或开头时,我将得到字符串,但如果数字放置在中间或任何其他位置,那么我期望的结果不会得到。\n当前输出如下图所示:
\n\n我认为我的正则表达式不正确。哪个正则表达式可以解决这些问题?或者是否有其他方法可以仅提取 pandas 数据框中的数字和字符串?
\n您的代码处于正确的轨道上,您只需要考虑小数和整数的可能性:
\n\ndf_num['colors_num'] = df_num.Colors.str.extract(r'(\\d+[.\\d]*)')\ndf_num['animals_num'] = df_num.Animals.str.extract(r'(\\d+[.\\d]*)')\ndf_num['colors_str'] = df_num.Colors.str.replace(r'(\\d+[.\\d]*)','')\ndf_num['animals_text'] = df_num.Animals.str.replace(r'(\\d+[.\\d]*)','')\n\n\n Colors Animals colors_num animals_num colors_str animals_text\n0 lila1.5 hu11nd 1.5 11 lila hund\n1 rosa2.5 12welpe 2.5 12 rosa welpe\n2 gelb3.5 13katze 3.5 13 gelb katze\n3 gr\xc3\xbcn4 s14chlange 4 14 gr\xc3\xbcn schlange\n4 rot5 vo15gel 5 15 rot vogel\n5 schwarz6 16papagei 6 16 schwarz papagei\n6 grau7 ku17h 7 17 grau kuh\n7 wei\xc3\x9f8 18ziege 8 18 wei\xc3\x9f ziege\n8 braun9 19pferd 9 19 braun pferd\n9 hellblau10 esel20 10 20 hellblau esel\nRun Code Online (Sandbox Code Playgroud)\n