熊猫系列地图

时间:2018-09-28 15:36:53

标签: python python-3.x pandas dataframe series

我有一个带有很多类别的DataFrame,但是我只想使用两个。我设法获得了想要的结果,但是在我的项目中没有被接受(“有更好的方法”)。使用2列-性别(M / F)和显示(1/0),我尝试获取4个变量:male1,male0,female1,female0,以使用它们创建条形图。

有人告诉我要使用pd.series.map函数,但是到处都找不到,也找不到很好的例子-也不确定如何从中获取4个变量。

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

pd.Series.map是不必要的。您可以在此处使用GroupBy并输出字典:

df = pd.DataFrame([['M', 0], ['M', 1], ['M', 1], ['F', 0], ['F', 0], ['F', 1]],
                  columns=['Gender', 'Showed'])

d = df.groupby(['Gender', 'Showed']).size().to_dict()

# {('F', 0): 2, ('F', 1): 1, ('M', 0): 1, ('M', 1): 2}

通常,应避免创建数量可变的变量。字典可让您有效地提取值,例如通过d[('F', 0)]代表女性,显示0。


但是,如果您真的必须使用map,则可以使用pd.Index.map版本:

d = df.groupby(['Gender', 'Showed']).size()

res = df.drop_duplicates()
res['Counts'] = res.set_index(['Gender', 'Showed']).index.map(d.get)

print(res)

  Gender  Showed  Counts
0      M       0       1
1      M       1       2
3      F       0       2
5      F       1       1

答案 1 :(得分:1)

这似乎是@Override public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.picture_row, parent, false); return new Holder(view); } 的情况(它是内置函数:D)

crosstab

输出:

import pandas as pd
df = pd.DataFrame([['M', 0], ['M', 1], ['M', 1], ['F', 0], ['F', 0], ['F', 1]],
                  columns=['Gender', 'Showed'])

pd.crosstab(df.Gender, df.Showed)

答案 2 :(得分:0)

您可以用4行简单的代码来完成此操作。

male0 = ((df['Gender'] == 'M') & (df['Showed'] == 0)).sum()
female0 = ((df['Gender'] == 'F') & (df['Showed'] == 0)).sum()
male1 = ((df['Gender'] == 'M') & (df['Showed'] == 1)).sum()
female1 = ((df['Gender'] == 'F') & (df['Showed'] == 1)).sum()

使用apply,因为您需要两个序列而不是一个序列,所以需要使用apply

male0 = df[['Gender', 'Showed']].apply(lambda row: row['Gender'] == 'M' and row['Showed'] == 0, axis=1).sum() 
female0 = df[['Gender', 'Showed']].apply(lambda row: row['Gender'] == 'F' and row['Showed'] == 0, axis=1).sum() 
male1 = df[['Gender', 'Showed']].apply(lambda row: row['Gender'] == 'M' and row['Showed'] == 1, axis=1).sum() 
female1 = df[['Gender', 'Showed']].apply(lambda row: row['Gender'] == 'F' and row['Showed'] == 1, axis=1).sum() 

使用groupby

counts = df.groupby(['Gender', 'Showed']).size().reset_index(name='Count')