python:如何在列中选择特定值并将它们变为新列

时间:2017-11-05 19:33:08

标签: python pandas

这是示例数据框

year    month  
2011    1

2012    1

2013    1

2011    2

2011    3

2013    2

我想选择year > 2012并将其设为新列"新年"。

2 个答案:

答案 0 :(得分:0)

如果您正在制作new_year == True,那么您可以执行以下操作。

df['new_year'] = df['year'] > 2012

你最终得到:

year  month  new_year
2011    1    False
2012    1    False
2013    1    True
2011    2    False

显然,你可以在这些专栏中找到你想要的东西:

bananas = 'bananas'
else_grapes = 'grapes'

df['new_year'] = np.where(df['year']>2012, bananas, else_grapes)

year  month  new_year
2011    1    'grapes'
2012    1    'grapes'
2013    1    'bananas'
2011    2    'grapes'

答案 1 :(得分:0)

这是您正在寻找的答案:

new_df = df[df['year'] > 2012]