如果pandas数据帧字符串列缺少值,如何小写?

问题描述 投票:39回答:6

以下代码不起作用。

import pandas as pd
import numpy as np
df=pd.DataFrame(['ONE','Two', np.nan],columns=['x']) 
xLower = df["x"].map(lambda x: x.lower())

如何调整它以获得xLower = ['one','two',np.nan]?效率很重要,因为真正的数据框架是巨大的。

python string pandas missing-data
6个回答
114
投票

用pandas vectorized string methods;如在文档中:

这些方法会自动排除缺失/ NA值

.str.lower()是那里的第一个例子;

>>> df['x'].str.lower()
0    one
1    two
2    NaN
Name: x, dtype: object

14
投票

另一个可能的解决方案,如果列不仅有字符串而且还有数字,则使用astype(str).str.lower()to_string(na_rep=''),否则,如果数字不是字符串,则降低时它将返回NaN,因此:

import pandas as pd
import numpy as np
df=pd.DataFrame(['ONE','Two', np.nan,2],columns=['x']) 
xSecureLower = df['x'].to_string(na_rep='').lower()
xLower = df['x'].str.lower()

然后我们有:

>>> xSecureLower
0    one
1    two
2   
3      2
Name: x, dtype: object

并不是

>>> xLower
0    one
1    two
2    NaN
3    NaN
Name: x, dtype: object

编辑:

如果你不想失去NaN,那么使用map会更好,(来自@ wojciech-walczak和@ cs95评论)它会看起来像这样

xSecureLower = df['x'].map(lambda x: x.lower() if isinstance(x,str) else x)

6
投票

可能的解决方案:

import pandas as pd
import numpy as np

df=pd.DataFrame(['ONE','Two', np.nan],columns=['x']) 
xLower = df["x"].map(lambda x: x if type(x)!=str else x.lower())
print (xLower)

结果是:

0    one
1    two
2    NaN
Name: x, dtype: object

虽然不确定效率。


2
投票

Pandas >= 0.25: Remove Case Distinctions with str.casefold

从v0.25开始,我推荐使用“向量化”字符串方法str.casefold,如果你正在处理unicode数据(无论字符串或unicodes如何都可以使用):

s = pd.Series(['lower', 'CAPITALS', np.nan, 'SwApCaSe'])
s.str.casefold()

0       lower
1    capitals
2         NaN
3    swapcase
dtype: object

另请参阅相关的GitHub问题GH25405

casefold适合更具侵略性的折叠比较。它还优雅地处理NaN(就像str.lower一样)。

But why is this better?

与unicodes有所不同。以python str.casefold docs为例,

Casefolding类似于lowercasing但更具攻击性,因为它旨在删除字符串中的所有大小写区别。例如,德语小写字母'ß'相当于"ss"。由于它已经是小写的,lower()'ß'无能为力; casefold()将其转换为"ss"

比较lower的输出,

s = pd.Series(["der Fluß"])
s.str.lower()

0    der fluß
dtype: object

casefold

s.str.casefold()

0    der fluss
dtype: object

另见Python: lower() vs. casefold() in string matching and converting to lowercase


1
投票

你也可以尝试这个,

df= df.applymap(lambda s:s.lower() if type(s) == str else s)

1
投票

可能正在使用List理解

import pandas as pd
import numpy as np
df=pd.DataFrame(['ONE','Two', np.nan],columns=['Name']})
df['Name'] = [str(i).lower() for i in df['Name']] 

print(df)

0
投票

复制您的Dataframe列并简单地应用

df = data ['x'] newdf = df.str.lower()

© www.soinside.com 2019 - 2024. All rights reserved.