“transpose” 一个 Pandas Series

4
我有一个包含ID列和一些特征列的DataFrame。我想查看每列值有多少唯一的ID。以下代码可行,但是我想知道是否有更好的方法来替代to_frame().unstack().unstack()部分,该部分将.describe()系列结果转置为DataFrame,其中列是百分位数、最大值、最小值等。
def unique_ids(df):
    rows = []
    for col in sorted(c for c in df.columns if c != id_col):
        v = df.groupby(col)[id_col].nunique().describe()
        v = v.to_frame().unstack().unstack()  # Transpose
        v.index = [col]
        rows.append(v)

    return pd.concat(rows)
1个回答

8

看起来你需要进行更改:

v = v.to_frame().unstack().unstack()

to

v = v.to_frame().T

可以使用transpose函数对最终的DataFrame进行转置,同时也可以通过col参数来重命名列:

df = pd.DataFrame({'ID':[1,1,3],
                   'E':[4,5,5],
                   'C':[7,8,9]})

print (df)
   C  E  ID
0  7  4   1
1  8  5   1
2  9  5   3

def unique_ids(df):
    rows = []
    id_col = 'ID'
    for col in sorted(c for c in df.columns if c != id_col):
        v = df.groupby(col)[id_col].nunique().describe().rename(col)
        rows.append(v)
    return pd.concat(rows, axis=1).T

print (unique_ids(df))
   count  mean       std  min   25%  50%   75%  max
C    3.0   1.0  0.000000  1.0  1.00  1.0  1.00  1.0
E    2.0   1.5  0.707107  1.0  1.25  1.5  1.75  2.0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接