我怎样才能实现SQL的的等价物IN和NOT IN?
我有一个包含所需值的列表.这是场景:
df = pd.DataFrame({'countries':['US','UK','Germany','China']})
countries = ['UK','China']
# pseudo-code:
df[df['countries'] not in countries]
Run Code Online (Sandbox Code Playgroud)
我目前的做法如下:
df = pd.DataFrame({'countries':['US','UK','Germany','China']})
countries = pd.DataFrame({'countries':['UK','China'], 'matched':True})
# IN
df.merge(countries,how='inner',on='countries')
# NOT IN
not_in = df.merge(countries,how='left',on='countries')
not_in = not_in[pd.isnull(not_in['matched'])]
Run Code Online (Sandbox Code Playgroud)
但这似乎是一个可怕的kludge.任何人都可以改进吗?
我有一个DataFrame df:
A B
a 2 2
b 3 1
c 1 3
Run Code Online (Sandbox Code Playgroud)
我想根据以下标准创建一个新列:
如果排 A == B: 0
如果排A > B: 1
如果排 A < B: -1
所以鉴于上表,它应该是:
A B C
a 2 2 0
b 3 1 1
c 1 3 -1
Run Code Online (Sandbox Code Playgroud)
对于if else我这样做的典型情况np.where(df.A > df.B, 1, -1),pandas是否提供了一个特殊的语法来一步解决我的问题(无需创建3个新列然后组合结果)?
我有这个代码(可以工作) - 一组嵌套的条件语句来设置数据帧的'paragenesis1'行中的值(myOxides ['cpx']),具体取决于帧的各个其他行中的值.
我对python和编程很新.我在想我应该编写一个函数来执行此操作,但是如何应用元素元素呢?这是我发现的唯一方法,以避免"系列的真值是模糊的"错误.
任何帮助非常感谢!
myOxides['cpx'].loc['paragenesis1'] = np.where(
((cpxCrOx>=0.5) & (cpxAlOx<=4)),
"GtPeridA",
np.where(
((cpxCrOx>=2.25) & (cpxAlOx<=5)),
"GtPeridB",
np.where(
((cpxCrOx>=0.5)&
(cpxCrOx<=2.25)) &
((cpxAlOx>=4) & (cpxAlOx<=6)),
"SpLhzA",
np.where(
((cpxCrOx>=0.5) &
(cpxCrOx<=(5.53125 -
0.546875 * cpxAlOx))) &
((cpxAlOx>=4) &
(cpxAlOx <= ((cpxCrOx -
5.53125)/ -0.546875))),
"SpLhzB",
"Eclogite, Megacryst, Cognate"))))
Run Code Online (Sandbox Code Playgroud)
要么;
df.loc['a'] = np.where(
(some_condition),
"value",
np.where(
((conditon_1) & (condition_2)),
"some_value",
np.where(
((condition_3)& (condition_4)),
"some_other_value",
np.where(
((condition_5),
"another_value",
"other_value"))))
Run Code Online (Sandbox Code Playgroud) 我有这个数据框:
+------+--------------+------------+
| ID | Education | Score |
+------+--------------+------------+
| 1 | High School | 7.884 |
| 2 | Bachelors | 6.952 |
| 3 | High School | 8.185 |
| 4 | High School | 6.556 |
| 5 | Bachelors | 6.347 |
| 6 | Master | 6.794 |
+------+--------------+------------+
Run Code Online (Sandbox Code Playgroud)
我想创建一个对分数列进行分类的新列。我想给它贴上标签:“差”、“好”、“非常好”。
这可能看起来像这样:
+------+--------------+------------+------------+
| ID | Education | Score | Labels |
+------+--------------+------------+------------+
| 1 | High School | 7.884 | Good |
| …Run Code Online (Sandbox Code Playgroud) pandas ×4
python ×4
dataframe ×3
conditional ×1
mapping ×1
numpy ×1
python-3.x ×1
sql-function ×1