Pandas的布尔索引

2024-04-19 01:14:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧

books = pd.Series(data = ['Great Expectations', 'Of Mice and Men', 'Romeo and Juliet', 'The Time Machine', 'Alice in Wonderland' ])
authors = pd.Series(data = ['Charles Dickens', 'John Steinbeck', 'William Shakespeare', ' H. G. Wells', 'Lewis Carroll' ])

user_1 = pd.Series(data = [3.2, np.nan ,2.5])
user_2 = pd.Series(data = [5., 1.3, 4.0, 3.8])
user_3 = pd.Series(data = [2.0, 2.3, np.nan, 4])
user_4 = pd.Series(data = [4, 3.5, 4, 5, 4.2])
dict_temp = {'Book Title':books, 'Author': authors, 'User 1': user_1, 'User 2':user_2, 'User 3': user_3, 'User 4': user_4}
pd.set_option('precision', 1)
temp_df = pd.DataFrame(dict_temp)

我的目标是选择所有用户评分为5.0的列。当我做以下工作时,它工作得很好。你知道吗

temp_df[temp_df == 5.0] 

但是,如果要选择用户评级为>;4.0的列,结果会有所不同。为什么会这样?你知道吗

temp_df[temp_df > 4.0]

下面是运行temp_df==5.0v/s temp_df>;4.0时的屏幕截图。我的问题是为什么我会看到书名和作者栏enter image description here?你知道吗

另外,我能通过这条线达到我想要的结果

temp_df[temp_df[['User 1','User 2','User 3','User 4']] > 4.0]

Tags: and用户gtdfdatanpnanbooks
1条回答
网友
1楼 · 发布于 2024-04-19 01:14:05

我可以用你的代码运行以下代码。你知道吗

我显式地将4.0设置为float,这可能会对您有所帮助,尽管对我来说这不是问题。你知道吗

temp_df = pd.DataFrame(dict_temp)
print(temp_df)
temp_df = temp_df[temp_df > float(4.0)]
print(temp_df)

输出

[5 rows x 6 columns]
            Book Title               Author   ...    User 3  User 4
0   Great Expectations      Charles Dickens   ...       NaN     NaN
1      Of Mice and Men       John Steinbeck   ...       NaN     NaN
2     Romeo and Juliet  William Shakespeare   ...       NaN     NaN
3     The Time Machine          H. G. Wells   ...       NaN     5.0
4  Alice in Wonderland        Lewis Carroll   ...       NaN     4.2

相关问题 更多 >