Python pandas数据框警告,建议使用.loc代替?

3

您好,我希望能够通过去除缺失信息和将所有字母转换为小写来操作数据。但对于小写转换,我收到了以下警告:

E:\Program Files Extra\Python27\lib\site-packages\pandas\core\frame.py:1808: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
  "DataFrame index.", UserWarning)
C:\Users\KubiK\Desktop\FamSeach_NameHandling.py:18: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

请查阅文档中的注意事项:http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

frame3["name"] = frame3["name"].str.lower()这行代码将frame3数据框中的"name"列转为小写。
C:\Users\KubiK\Desktop\FamSeach_NameHandling.py:19: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

请参阅文档中的注意事项:http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

frame3 ["ethnicity"] = frame3 ["ethnicity"].str.lower() 这行代码将把 "frame3" 中的 "ethnicity" 列转换为小写字母。
import pandas as pd
from pandas import DataFrame

# Get csv file into data frame
data = pd.read_csv("C:\Users\KubiK\Desktop\OddNames_sampleData.csv")
frame = DataFrame(data)
frame.columns = ["name", "ethnicity"]
name = frame.name
ethnicity = frame.ethnicity

# Remove missing ethnicity data cases
index_missEthnic = frame.ethnicity.isnull()
index_missName = frame.name.isnull()
frame2 = frame[index_missEthnic != True]
frame3 = frame2[index_missName != True]

# Make all letters into lowercase
frame3["name"] = frame3["name"].str.lower()
frame3["ethnicity"] = frame3["ethnicity"].str.lower()

# Test outputs
print frame3

这个警告似乎不是致命的(至少对于我的小样本数据来说),但我应该如何处理它?
样本数据
Name    Ethnicity
Thos C. Martin                              Russian
Charlotte Wing                              English
Frederick A T Byrne                         Canadian
J George Christe                            French
Mary R O'brien                              English
Marie A Savoie-dit Dugas                    English
J-b'te Letourneau                           Scotish
Jane Mc-earthar                             French
Amabil?? Bonneau                            English
Emma Lef??c                                 French
C., Akeefe                                  African
D, James Matheson                           English
Marie An: Thomas                            English
Susan Rrumb;u                               English
                                            English
Kaio Chan   

我很好奇你是否阅读了警告中提到的注意事项。它们在回答这个问题时有什么不足之处吗? - Paul H
1
我确实已经阅读了警告。这只是一个过于简化的示例,对于像我这样的新手程序员没有用处。即使我遵循有经验的程序员使用.loc的建议,仍然存在相同的警告(如下所示)。 - KubiK888
在我看来,这个例子与你的非常相似。在下面的答案中,你仍然是在使用副本进行赋值——换句话说,loc 在错误的一侧。请参见我在那篇帖子中的评论。 - Paul H
2个回答

3

不确定为什么需要这么多布尔值... 同时请注意,.isnull()无法捕获空字符串。 在应用.lower()之前过滤空字符串似乎也不是必要的。 但如果需要的话...对我来说这个方法行得通:

frame = pd.DataFrame({'name':['Abc Def', 'EFG GH', ''], 'ethnicity':['Ethnicity1','', 'Ethnicity2']})
print frame

    ethnicity     name
0  Ethnicity1  Abc Def
1               EFG GH
2  Ethnicity2         

name_null = frame.name.str.len() == 0
frame.loc[~name_null, 'name'] = frame.loc[~name_null, 'name'].str.lower()
print frame

    ethnicity     name
0  Ethnicity1  abc def
1               efg gh
2  Ethnicity2         

2
当您设置frame2/3时,请尝试使用如下的.loc方法:
frame2 = frame.loc[~index_missEthnic, :]
frame3 = frame2.loc[~index_missName, :]

我认为这可以解决你看到的错误:

frame3.loc[:, "name"] = frame3.loc[:, "name"].str.lower()
frame3.loc[:, "ethnicity"] = frame3.loc[:, "ethnicity"].str.lower()

您也可以尝试以下方法,虽然它并不能回答您的问题:
frame3.loc[:, "name"] = [t.lower() if isinstance(t, str) else t for t in frame3.name]
frame3.loc[:, "ethnicity"] = [t.lower() if isinstance(t, str) else t for t in frame3. ethnicity]

该函数将列中的任何字符串转换为小写字母,否则保持不变。


谢谢,我按照你的建议做了,但是仍然有以下警告信息。 - KubiK888
请在文档中查看注意事项:http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy frame3["ethnicity"] = frame3["ethnicity"].str.lower() - KubiK888
1
@KubiK888:顺便说一句,提供一些样本数据让用户可以玩弄它会很有帮助(而不是在您的计算机上使用csv文件)。 - Alexander
我尝试了你的第二组建议,但是相同的警告仍然存在。 - KubiK888
1
@Alexander,你仍在分配给副本。我认为你应该编辑你的答案以反映我上面的评论,这样未来的读者就不必滚动所有这些评论了。 - Paul H
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接