python pandas loc返回空数据帧

时间:2018-06-01 10:07:35

标签: python pandas

我正在尝试使用以下代码获取子集数据框:

dprev = "eiffel tower"

df.loc[df['place'] == dprev] -> returns empty

drandom = random.choice(df['place'].unique())

df.loc[df['place'] == drandom] -> returns the subset

为什么dprev是字符串变量时我没有看到同样的事情?

3 个答案:

答案 0 :(得分:0)

为此您不必使用df.loc

dprev = "eiffel tower"

df[df['place'] == dprev] 

See this answer

答案 1 :(得分:0)

您可以尝试将str.containscase=False

一起使用

<强>实施例

import pandas as pd

dprev = "eiffel tower"
df = pd.DataFrame({"place": ["eiffel tower", "Eiffel tower", "Hello"], "data":[1,2,3]})
print(df.loc[df['place'].str.contains(dprev, case=False)])

<强>输出:

   data         place
0     1  eiffel tower
1     2  Eiffel tower

答案 2 :(得分:0)

尝试这种方式:

dprev = "eiffel tower"
df = df.loc[df['place'].str.lower() == dprev]

或:

df = df.loc[df['place'].str.lower().str.contains(dprev)]