获取 Table 中元素相对于另一列的频率
Getting the Frequency of Elements in a Table With Respect to Another Column
我有一个关于根据列的频率将 table 转换为另一种格式并按另一列分组的问题。我确定以前有人问过这个问题,但我找不到正确的搜索关键字,所以我想我会问这个问题。
我有以下 table:
Patient
Diagnosis
Ralph
A
Ralph
A
Steve
B
我想将其转换为:
Patient
A
B
Ralph
2
0
Steve
0
1
如有任何帮助或指点,我们将不胜感激!我已经达到 df.groupby("Patient").Diagnosis.value_counts()
,但这并不包括对患者的所有诊断(即诊断计数为 0 的患者)。
正如 Shubham 评论的那样,您可以 cross tabulate:
import pandas as pd
df = pd.DataFrame({
'Patient': ['Ralph', 'Ralph', 'Steve'],
'Diagnosis': ['A', 'A', 'B'],
})
pd.crosstab(df.Patient, df.Diagnosis)
输出:
Diagnosis A B
Patient
Ralph 2 0
Steve 0 1
- 只是
len()
每个 患者 和 诊断
unstack()
生成 诊断 列
- 其余的是到达您的特定输出的详细信息
df = pd.read_csv(io.StringIO("""Patient Diagnosis
Ralph A
Ralph A
Steve B"""), sep="\t")
df = (df.groupby(["Patient","Diagnosis"]).agg(len)
.to_frame().unstack().droplevel(0, axis=1).fillna(0).astype(int)
.reset_index().rename_axis(None, axis=1)
)
Patient
A
B
0
Ralph
2
0
1
Steve
0
1
我有一个关于根据列的频率将 table 转换为另一种格式并按另一列分组的问题。我确定以前有人问过这个问题,但我找不到正确的搜索关键字,所以我想我会问这个问题。
我有以下 table:
Patient | Diagnosis |
---|---|
Ralph | A |
Ralph | A |
Steve | B |
我想将其转换为:
Patient | A | B |
---|---|---|
Ralph | 2 | 0 |
Steve | 0 | 1 |
如有任何帮助或指点,我们将不胜感激!我已经达到 df.groupby("Patient").Diagnosis.value_counts()
,但这并不包括对患者的所有诊断(即诊断计数为 0 的患者)。
正如 Shubham 评论的那样,您可以 cross tabulate:
import pandas as pd
df = pd.DataFrame({
'Patient': ['Ralph', 'Ralph', 'Steve'],
'Diagnosis': ['A', 'A', 'B'],
})
pd.crosstab(df.Patient, df.Diagnosis)
输出:
Diagnosis A B
Patient
Ralph 2 0
Steve 0 1
- 只是
len()
每个 患者 和 诊断 unstack()
生成 诊断 列- 其余的是到达您的特定输出的详细信息
df = pd.read_csv(io.StringIO("""Patient Diagnosis
Ralph A
Ralph A
Steve B"""), sep="\t")
df = (df.groupby(["Patient","Diagnosis"]).agg(len)
.to_frame().unstack().droplevel(0, axis=1).fillna(0).astype(int)
.reset_index().rename_axis(None, axis=1)
)
Patient | A | B | |
---|---|---|---|
0 | Ralph | 2 | 0 |
1 | Steve | 0 | 1 |