只是一个(有点)简单的问题-如果我有以下形式的数列中的数据帧1.305.000, 4.65, 99.9, 443.111.34000
,我怎样才能将它们转换为“正确”的格式:1305.000, 4.65, 99.9, 443111.34000
?
如果有帮助,则从.csv
文件的某一列中获取值,例如“总净收入”:
以代码块形式:
Day Service Total Net Revenue
0 1 te 1.305.000
1 1 as 4.65
2 2 qw 99.9
3 3 al 443.111.34000
4 6 al 443.111.34000
5 6 te 1.305.000
6 7 pp 200
7 7 te 1.305.000
8 7 al 443.111.34000
9 7 te 1.305.000
另一种基于反馈的形式:
[{'Day': 1, 'Service': 'te', 'Total Net Revenue': '1.305.000'},
{'Day': 1, 'Service': 'as', 'Total Net Revenue': '4.65'},
{'Day': 2, 'Service': 'qw', 'Total Net Revenue': '99.9'},
{'Day': 3, 'Service': 'al', 'Total Net Revenue': '443.111.34000'},
{'Day': 6, 'Service': 'al', 'Total Net Revenue': '443.111.34000'},
{'Day': 6, 'Service': 'te', 'Total Net Revenue': '1.305.000'},
{'Day': 7, 'Service': 'pp', 'Total Net Revenue': '200'},
{'Day': 7, 'Service': 'te', 'Total Net Revenue': '1.305.000'},
{'Day': 7, 'Service': 'al', 'Total Net Revenue': '443.111.34000'},
{'Day': 7, 'Service': 'te', 'Total Net Revenue': '1.305.000'}]
我似乎找不到任何参考,一些见识将受到深深的赞赏。谢谢!
这不是一个大熊猫问题,它实际上是在询问如何将看起来奇怪的字符串转换为数字(标记:数字格式)。
以下函数会将这些字符串转换为所需的数字:
import unittest
def cleanup(s: str) -> float:
parts = s.split('.')
if len(parts) > 1:
s = ''.join(parts[:-1]) + '.' + parts[-1]
return float(s)
class TestCleanup(unittest.TestCase):
def test_cleanup(self):
self.assertEqual(200, cleanup('200'))
self.assertEqual(4.65, cleanup('4.65'))
self.assertEqual(1305, cleanup('1.305.000'))
self.assertEqual(443111.34, cleanup('443.111.34000'))
您可能会考虑使用Decimal
那些是否为货币数字,这会激发“缩放整数”方法。
对于现有数据框.apply()
,cleanup()
函数很简单:
df['numeric_revenue'] = df['total_net_revenue'].apply(cleanup)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句