我有一个这样的Pandas数据框:
A B C D
0 month month+1 quarter+1 season+1
1 season month+5 quarter+3 season+2
2 day month+1 quarter+2 season+1
3 year month+3 quarter+4 season+2
4 quarter month+2 quarter+1 season+1
5 month month+4 quarter+1 season+2
我想基于多个IF条件插入一个名为“ E”的新列。如果“ A”列等于“月”,则返回“ B”中的值,如果“ A”列等于“季度”,则返回“ C”中的值,如果“ A”列等于“季节”,则返回“ D”中的值,如果没有,则返回“ A”列中的值
A B C D E
0 month month+1 quarter+1 season+1 month+1
1 season month+5 quarter+3 season+2 season+2
2 day month+1 quarter+2 season+1 day
3 year month+3 quarter+4 season+2 year
4 quarter month+2 quarter+1 season+1 quarter+1
5 month month+4 quarter+1 season+2 month+4
我在执行此操作时遇到了麻烦。我试着玩一个函数,但是没有用。看看我的尝试:
def f(row):
if row['A'] == 'month':
val = ['B']
elif row['A'] == 'quarter':
val = ['C']
elif row['A'] == 'season':
val = ['D']
else:
val = ['A']
return val
df['E'] = df.apply(f, axis=1)
编辑:将最后一个else
更改为“ A”列
参考方案
只需使用np.select
c1 = df['A'] == 'month'
c2 = df['A'] == 'quarter'
c3 = df['A'] == 'season'
df['E'] = np.select([c1, c2, c3], [df['B'], df['C'], df['D']], df['A'])
Out[271]:
A B C D E
0 month month+1 quarter+1 season+1 month+1
1 season month+5 quarter+3 season+2 season+2
2 day month+1 quarter+2 season+1 day
3 year month+3 quarter+4 season+2 year
4 quarter month+2 quarter+1 season+1 quarter+1
5 month month+4 quarter+1 season+2 month+4
Python Pandas:按分组分组,平均? - python我有一个像这样的数据框:cluster org time 1 a 8 1 a 6 2 h 34 1 c 23 2 d 74 3 w 6 我想计算每个集群每个组织的平均时间。预期结果:cluster mean(time) 1 15 ((8+6)/2+23)/2 2 54 (74+34)/2 3 6 我不知道如何在熊猫中做到这一点,有人可以帮忙吗? 参考方案 如…
Python Pandas:在多列上建立布尔索引 - python尽管至少有关于如何在Python的pandas库中为DataFrame编制索引的two good教程,但我仍然无法在一个以上的列上找到一种优雅的SELECT编码方式。>>> d = pd.DataFrame({'x':[1, 2, 3, 4, 5], 'y':[4, 5, 6, 7, 8]}) >…
Python Pandas:选择索引范围 - pythondatas = [['RAC1','CD0287',1.52], ['RAC1','CD0695',2.08], ['RAC1','ADN103-1',2.01], ['RAC3','CD0258',…
python pandas:按行对条件进行分组 - python我有一个大的pandas数据框,试图从中形成一些行的对。我的df如下所示:object_id increment location event 0 1 d A 0 2 d B 0 3 z C 0 4 g A 0 5 g B 0 6 i C 1 1 k A 1 2 k B ... ... ... ... 对象ID描述特定的对象。增量是每次发生某事(跟踪订单)时…
Python-Excel导出 - python我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…