如何在同一数据框中创建具有来自字典的键名的新列?
How can I create new columns having key names from dictionary in same dataframe?
我尝试使用您的代码来转换它:
column of dictionaries
进入 2 个新栏目:得分和获胜者
但是当我使用这段代码时:
data = data.join(
pd.DataFrame.from_records(
data["score"].mask(data.score.isna(), {}).tolist()
).add_prefix("score_")
)
print(data.head())
印刷品给我这个:new columns added
很明显,我为字典中的每个字符创建了一个新列。
你能帮我解决这个问题吗?
您应该将 col of dicts 作为 dicts 数组传递,例如:
d = [{'score': [1], 'winner': "L"}, {'score': [1], 'winner': "W"}]
df = pd.DataFrame(data=d)
输出 (df.head()):
score winner
0 [1] L
1 [1] W
然后用于解压缩数组元素(应该是整数):df["score"] = df["score"].apply(sum)
我尝试使用您的代码来转换它: column of dictionaries
进入 2 个新栏目:得分和获胜者
但是当我使用这段代码时:
data = data.join(
pd.DataFrame.from_records(
data["score"].mask(data.score.isna(), {}).tolist()
).add_prefix("score_")
)
print(data.head())
印刷品给我这个:new columns added
很明显,我为字典中的每个字符创建了一个新列。
你能帮我解决这个问题吗?
您应该将 col of dicts 作为 dicts 数组传递,例如:
d = [{'score': [1], 'winner': "L"}, {'score': [1], 'winner': "W"}]
df = pd.DataFrame(data=d)
输出 (df.head()):
score winner
0 [1] L
1 [1] W
然后用于解压缩数组元素(应该是整数):df["score"] = df["score"].apply(sum)