![](/img/trans.png)
[英]Append string to matching columns (with various data types) in the same Pandas dataframe
[英]Split string to various data types
我想转换以下字符串:
s = '1|2|a|b'
至
[1, 2, 'a', 'b']
是否可以在一行中进行转换?
是否可以在一行中进行转换?
是的 ,有可能。 但是怎么样?
该方法的算法
使用str.split
将字符串拆分为其组成部分。 这个的输出是
>>> s = '1|2|a|b' >>> s.split('|') ['1', '2', 'a', 'b']
现在我们有一半的问题。 接下来,我们需要循环遍历拆分字符串,然后检查它们中的每一个是字符串还是int。 为此,我们使用
str.isdigit
用于查找元素是int
还是str
。 列表理解可以很容易地写成[i for i in s.split('|')]
。 但是我们如何在那里添加if
子句呢? 这在单行列表理解中有所介绍:if-else变体 。 现在我们知道哪些元素都是int
而哪些不是int
,我们可以轻松地在其上调用builtin int
。
因此最终的代码看起来像
[int(i) if i.isdigit() else i for i in s.split('|')]
现在进行一个小型演示,
>>> s = '1|2|a|b'
>>> [int(i) if i.isdigit() else i for i in s.split('|')]
[1, 2, 'a', 'b']
我们可以看到,输出是预期的。
请注意,如果要转换的类型很多,则此方法不适用。
您不能在一行中为负数或大量混合类型执行此操作,但您可以使用可以使用ast.literal_eval
为多个类型工作的函数:
from ast import literal_eval
def f(s, delim):
for ele in s.split(delim):
try:
yield literal_eval(ele)
except ValueError:
yield ele
s = '1|-2|a|b|3.4'
print(list(f(s,"|")))
[1, -2, 'a', 'b', 3.4]
如果允许辅助函数,则可以“在一行中”进行任意多次或复杂的转换。 Python本身没有“将此字符串转换为它应该表示的类型”函数,因为它“应该”表示的是模糊的,可能会从应用程序更改为应用程序。
def convert(input):
converters = [int, float, json.loads]
for converter in converters:
try:
return converter(input)
except (TypeError, ValueError):
pass
# here we assume if all converters failed, it's just a string
return input
s = "1|2.3|a|[4,5]"
result = [convert(x) for x in s.split("|")]
另一种方法是使用map
内置方法:
>>> s='1|2|a|b'
>>> l = map(lambda x: int(x) if x.isdigit() else x, s.split('|'))
>>> l
[1, 2, 'a', 'b']
如果是Python3,那么:
>>> s='1|2|a|b'
>>> l = list(map(lambda x: int(x) if x.isdigit() else x, s.split('|')))
>>> l
[1, 2, 'a', 'b']
由于Python3中的map
会给出生成器,因此必须将其转换为list
如果你有各种各样的数据类型(超过str和int),我相信这样做。
s = '1|2|a|b|[1, 2, 3]|(1, 2, 3)'
print [eval(x) if not x.isalpha() else x for x in s.split("|")]
# [1, 2, 'a', 'b', [1, 2, 3], (1, 2, 3)]
如果存在诸如“b1”之类的元素,则会失败
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.