将值替换为拆分中的值

2024-10-03 23:26:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据库:

X_MA2_period=4.4 ,sh2=2 ,Edu_km_hl=8.4 ,Edu_km_sd=5.6 ,Edu_km_sr=5.6 ,Edu_km_v1440=0.6
X_MA2_period=4.4 ,sh2=2 ,Edu_km_hl=8.4 ,Edu_km_sd=5.6 ,Edu_km_sr=5.6 ,Edu_km_v1440=0.6
X_MA2_period=5.8 ,sh2=2 ,Edu_km_hl=9 ,Edu_km_sd=5.6 ,Edu_km_sr=5.8 ,Edu_km_v1440=0.64
X_MA2_period=4 ,sh2=5 ,Edu_km_hl=3.2 ,Edu_km_sd=5.6 ,Edu_km_sr=9 ,Edu_km_v1440=0.5

4413行x 52列

我需要将“=”的左侧作为每列的名称(例如:X_MA2_period),右侧作为该列中的值列表。我试过这个:

lista_colunas = []
for i in range(0, df.shape[1]):
    lista_colunas.append(df.iloc[0][i].split('=')[0])
df.columns = lista_colunas

第一部分没问题。但是

df = pd.read_csv('data.txt')

for index, row in df.iterrows():
    row[50] = row[50].split('=')[1]
    print(row[50]) # I tried print to see if is replaced, and it is. But...

print(df.iloc[0][50])
print(df)

所有单元格都有旧值,在拆分之前。。。欢迎任何帮助


Tags: dfforsdhlperiodrowprintedu
1条回答
网友
1楼 · 发布于 2024-10-03 23:26:38

您可以执行以下操作:

# get columns
columns = [v.split('=')[0] for v in df.loc[0]]

# Keep the values to the right of the '=' in the columns
for c in df.columns:
    df.loc[:, c] = df.loc[:, c].str.split('=').str[1]

# Rename the columns
df.columns = columns

df.head()

输出为: Code output

相关问题 更多 >