我有pandas数据框列,我想用空格''替换Hyperparameters列字符串。
我在下面的命令中尝试将其替换为空格,但不起作用,请让我知道如何将其替换为空白吗?
new_df = df.Hyperparameters.str.replace('{'max_samples':20,'contamination':','')
df:
Accuracy Hyperparameters
0.902475 {'max_samples': 20, 'contamination': 0.1647368...
0.488819 {'max_samples': 100, 'contamination': 0.697719...
0.834296 {'max_samples': 70, 'contamination': 0.2875438...
0.608662 {'max_samples': 80, 'contamination': 0.5749122...
0.505224 {'max_samples': 10, 'contamination': 0.6731578...
0.792928 {'max_samples': 80, 'contamination': 0.3415789...
转换为:
new_df:
Accuracy Hyperparameters
0.902475 0.1647368...
0.488819 0.697719...
0.834296 0.2875438...
0.608662 0.5749122...
0.505224 0.6731578...
0.792928 0.3415789...
答案 0 :(得分:0)
使用df.apply
import pandas as pd
df = pd.DataFrame({"Accuracy": [0.902475, 0.488819], "Hyperparameters": [{'max_samples': 20, 'contamination': 0.1647368}, {'max_samples': 100, 'contamination': 0.697719}]})
df["Hyperparameters"] = df["Hyperparameters"].apply(lambda x: x["contamination"])
print(df)
输出:
Accuracy Hyperparameters
0 0.902475 0.164737
1 0.488819 0.697719
Hyperparameters
列中有一个字典