如何在Python中创建类似于excel的计算字段?

时间:2019-01-29 15:35:50

标签: python pandas

我想将数据透视表从Excel迁移到python,以使用可视化及其他功能。我在excel中使用了两个计算字段,所以我想知道是否可以对Pandas使用类似的想法? 谢谢。

1 个答案:

答案 0 :(得分:2)

不确定您的数据是什么样子,但是使用熊猫绝对可以。

这是一个例子:

    age name
0   17  John
1   23  Mark
2   4   Alice
3   27  Alice

输出1

np.where

使用np.where(condition, true value, false value)方法创建计算字段
此方法背后的逻辑: df['adult_indicator'] = np.where(df.age >= 18, 1, 0)
查找更多here


    age name    adult_indicator
0   17  John    0
1   23  Mark    1
2   4   Alice   0
3   27  Alice   1

Output2

pivot

pandas模块中应用df.pivot(index='name', columns='age', values='adult_indicator') 方法

    age 4   17  23  27
name                
Alice   0.0 NaN NaN 1.0
John    NaN 0.0 NaN NaN
Mark    NaN NaN 1.0 NaN

Output3

data_df = pd.DataFrame([3, 1, 2, 4], index=['a', 'b', 'c', 'd']).transpose()
points_df = pd.DataFrame([3.5, 0.5, 1.75, 4.25], index=['a', 'b', 'c', 'd']).transpose()

plt.figure()
sns.barplot(data=data_df)
sns.scatterplot(data=points_df.T, legend=False, zorder=10)