大熊猫保持数字部分

时间:2016-08-30 07:58:09

标签: python string pandas replace numeric

我有一组数据,如:

        0       1 
0  type 1  type 2
1  type 3  type 4

如何将其转移到:

   0  1
0  1  2
1  3  4

使用applytransform函数

进行更新

4 个答案:

答案 0 :(得分:3)

选项1

$rootScope.innerHTML = service.gethtml;

选项2

df.stack().str.replace('type ', '').unstack()

选项3

df.stack().str.split().str[-1].unstack()

enter image description here

时序

结论 @ jezreal' s是最好的。没有循环,没有堆叠。

<强>

20,000 by 200

# pandas version 0.18.1 +
df.stack().str.extract('(\d+)', expand=False).unstack()

# pandas version 0.18.0 or prior
df.stack().str.extract('(\d+)').unstack()

enter image description here

答案 1 :(得分:3)

>>> df.apply(lambda x: x.str.replace('type ','').astype(int))
   0  1
0  1  2
1  3  4
如果您不需要转换为int

,请删除.astype(int)

答案 2 :(得分:3)

你可以使用DataFrame.replace

print (df.replace({'type ': ''}, regex=True))
   0  1
0  1  2
1  3  4

答案 3 :(得分:2)

您可以使用applymap和正则表达式(import re):

df = df.applymap(lambda x: re.search(r'.*(\d+)', x).group(1))

如果您希望数字为整数:

df = df.applymap(lambda x: int(re.search(r'.*(\d+)', x).group(1)))

即使您有其他文本而不是type,这也会有效,并且只有整数(即'type 1.2'会破坏此代码),因此您必须对其进行修改。

另请注意,如果未找到任何数字(即'type'),此代码将失败。您可能希望创建一个可以处理这些错误的函数,而不是lambda

def extract_digit(x):
     try:
         return int(re.search(r'.*(\d+)', x).group(1))
     except (ValueError, AttributeError):
         # return the existing value
         return x

df = df.applymap(lambda x: extract_digit(x))