简体   繁体   中英

keyerror while tring to access pandas dataframe column

I am trying to process create a pandas dataframe column and access the column by using its column name which gives an error KeyError: 'cluster'

Code

import pandas as pd
from scipy.cluster.hierarchy import fclusterdata

max_dist = 3
points = [(3, 2), (6, 2), (6, 5), (10, 1), (12, -2), (5, 7)]
clusters = fclusterdata(points, t=max_dist, criterion='distance')
clustered_points = (pd.DataFrame(points, columns=['x', 'y'], index=clusters)
                      .rename_axis(index='cluster'))
clustered_points['cluster']

How this error can be solved.

import pandas as pd
    from scipy.cluster.hierarchy import fclusterdata
    
    max_dist = 3
    points = [(3, 2), (6, 2), (6, 5), (10, 1), (12, -2), (5, 7)]
    clusters = fclusterdata(points, t=max_dist, criterion='distance')
    
    df = pd.DataFrame(points, columns=['x', 'y'])
    df["clusters"] = clusters
    print(df["clusters"])

If you're trying to access the column "clusters" I think this is the way to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM