python - pandas 应用返回 NaN

标签 python pandas

我有一个 json,我将其转换为字典,然后使用字典中存在的某些键值对创建一个数据框

# json
a = """{
    "cluster_id": 3,
    "cluster_observation_data": [[1, 2, 3, 4, 5, 6, 7, 8], [2, 3, 4, 5, 6, 7, 8, 1]],
    "cluster_observation_label": [0, 1],
    "cluster_centroid": [1, 2, 3, 4, 5, 6, 7, 10],
    "observation_id":["id_xyz_999","id_abc_000"]
}"""

# convert to dictionary
data = json.loads(a)
sub_dict = dict((k, data[k]) for k in ('cluster_observation_data', 'cluster_observation_label'))
train = pd.DataFrame.from_dict(sub_dict, orient='columns')

将其转换为 ddataframe 后,我尝试计算其与 cluster_centroid 的欧几里得距离存在于 data字典。该函数工作正常,但在最后 train我得到 NaN 的数据框

def distance_from_center(row):
    centre = data['cluster_centroid']
    obs_data = row[0]
    print('obs_data', obs_data)
    print('\n\n\n\n')
    print('center', centre)
    # print(type(obs_data))
    # print(type(centre))
    dist = sum([(a - b)**2 for a, b in zip(centre, obs_data)])
    print(dist)
    return dist

train.loc[:, 'center_dist'] = train.loc[:, ['cluster_observation_data']].apply(distance_from_center)

我不知道我哪里出了问题。即使是一个小提示也可以。

最佳答案

您需要传递轴,例如:

train.loc[:, 'center_dist'] = train.loc[:, ['cluster_observation_data']].apply(distance_from_center, 1)

原因是您想将函数单独应用于每个列表。 Documentation说:

1 or ‘columns’: apply function to each row

关于python - pandas 应用返回 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47428530/

相关文章:

python: TypeError: %c 需要 int 或 char

python - 3D 张量输入到 keras 或 tensorflow 中的嵌入层?

python - 将数字字符串转换为数字列表

pandas - 在 scikit-learn 中使用 Featureunion 为 tfidf 组合两个 Pandas 列

python - 如何从数据框的列中获取唯一名称

python - Python 中的字典分组和聚合列表

python - 可以在 pytest 中包含 pytest 吗?

python - Flask-安全寄存器重定向

Python:用单词列表替换句子中的一个单词,并将新句子放在 pandas 的另一列中

pandas - 绘制包含 NaN 的 Pandas 数据框