我有一个包含两列的数据框,一列用于名称,一列用于字符串值。 我正在尝试按名称计算选择字符串值的频率。
我尝试了pandas.pivot_table和pandas.DataFrame.groupby,但我想创建一个全新的数据框,而不是聚合。
例如,我有一个数据框:
import pandas as pd
import numpy as np
data = np.array([['John', 'x'], ['John', 'x'], ['John', 'x'], ['John', 'y'], ['John', 'y'], ['John', 'a'],
['Will', 'x'], ['Will', 'z']])
df = pd.DataFrame(data, columns=['name','str_value'])
df
结果为:
name str_value
0 John x
1 John x
2 John x
3 John y
4 John y
5 John a
6 Will x
7 Will z
预期结果将是:
name x y z
0 John 3 2 0
1 Will 1 0 1
,另外:
name x y z
0 John True True False
1 Will True False True
我只想选择x,y,z,然后根据返回值是0还是NaN返回True或False。
编辑: 谢谢你的回答。 这些效果很好,但是输出具有子组“ str_value”:
str_value x y z
name
John True True False
Will True False True
有没有办法删除它,所以我在同一级别上具有“名称”,“ x”,“ y”,“ z”? 使用.reset_index()我得到:
str_value name x y z
0 John True True False
1 Will True False True
现在索引的名称是“ str_value”吗?我可以重命名或删除它吗?
答案 0 :(得分:2)
混合使用groupby
和pivot
:
total = df.groupby(["name", "str_value"]).size().reset_index(level=1, name="total")
counts = total.pivot(columns="str_value", values="total").fillna(0).drop(columns=["a"])
bools = counts > 0.0
答案 1 :(得分:2)
除了其他出色的答案外,您还可以将groupby
unstack
和astype(bool)
的组合用于一个衬纸:
df1 = df.loc[df.str_value != 'a'] # remove a as requested.
df2 = df1.groupby(["name", "str_value"])["str_value"].count().unstack().fillna(False).astype(
bool)
print(df2)
name x y z
0 John True True False
1 Will True False True
答案 2 :(得分:1)
您可以尝试:
df.groupby(["name", "str_value"]).size().unstack()[['x', 'y', 'z']].gt(0)
说明:
print(df.groupby(["name", "str_value"]).size())
# John a 1
# x 3
# y 2
# Will x 1
# z 1
# dtype: int64
unstack
取消堆叠print(df.groupby(["name", "str_value"]).size().unstack())
# str_value a x y z
# name
# John 1.0 3.0 2.0 NaN
# Will NaN 1.0 NaN 1.0
print(df.groupby(["name", "str_value"]).size().unstack()[['x', 'y', 'z']])
# str_value x y z
# name
# John 3.0 2.0 NaN
# Will 1.0 NaN 1.0
gt
比较大于0的值:result = df.groupby(["name", "str_value"]).size().unstack()[['x', 'y', 'z']].gt(0)
print(result)
# str_value x y z
# name
# John True True False
# Will True False True