Python 如何使用pandas仅循环文本文件中的特定列?

Python 如何使用pandas仅循环文本文件中的特定列?,python,pandas,Python,Pandas,我只想做这个循环: for col in result.columns: result[col] = result[col].str.strip("{} ") 用于列“1H.L”和“1H_2.L”,因为其他列不是字符串 我的代码是: import pandas as pd result = {} text = 'fe' filename = 'fe_yellow.xpk' if text == 'ee': df = pd.read_csv('peaks_ee.xpk', s

我只想做这个循环:

for col in result.columns:
    result[col] = result[col].str.strip("{} ")
用于列“1H.L”和“1H_2.L”,因为其他列不是字符串

我的代码是:

import pandas as pd

result = {}
text = 'fe'
filename = 'fe_yellow.xpk'

if text == 'ee':
    df = pd.read_csv('peaks_ee.xpk', sep=" ",skiprows=5)

    shift1= df["1H.P"]
    shift2= df["1H_2.P"]

    if filename == 'ee_pinkH1.xpk':
        mask = ((shift1>5.1) & (shift1<6)) & ((shift2>7) & (shift2<8.25))
    elif filename == 'ee_pinkH2.xpk':
       mask = ((shift1>3.25)&(shift1<5))&((shift2>7)&(shift2<8.5))

result = df[mask]
result = result[["1H.L","1H.P","1H_2.L","1H_2.P"]]

for col in result.columns:
    result[col] = result[col].str.strip("{} ")
result.drop_duplicates(keep='first', inplace=True)

tclust_atom=open("tclust_ppm.txt","w+")
result.to_string(tclust_atom, header=False)
我希望我的输出看起来像

1.H1' 5.82020 0.3
2.H8 7.61004 0.3
1.H8 8.13712 0.3
2.H1' 5.90291 0.3

第一列来自“1H.L”和“1H_2.L”列,第二列来自“1H.p”和“1H_2.p”,第三列是我想为每一行写的内容。我该怎么做呢?

你为什么不能直截了当地说

for col in result.columns:
    if col == ("1H.L" | "1H_2.L"):
        result[col] = result[col].str.strip("{} ")

你为什么不能直截了当地说

for col in result.columns:
    if col == ("1H.L" | "1H_2.L"):
        result[col] = result[col].str.strip("{} ")

您只需传递列名称列表,即

result = pd.DataFrame({"1H.L":['{Nice}','{SO}'],"1H_2.L":['{Nice}','{SO}'],"2H.L":['Nice','SO']})

for col in ['1H.L','1H_2.L']:
    result[col] = result[col].str.strip("{} ")
输出:

1H.L 1H_2.L 2H.L 0 Nice Nice Nice 1 SO SO SO 1H.L 1H_2.L 2H.L 0很好 1一般
您只需传递列名称列表,即

result = pd.DataFrame({"1H.L":['{Nice}','{SO}'],"1H_2.L":['{Nice}','{SO}'],"2H.L":['Nice','SO']})

for col in ['1H.L','1H_2.L']:
    result[col] = result[col].str.strip("{} ")
输出:

1H.L 1H_2.L 2H.L 0 Nice Nice Nice 1 SO SO SO 1H.L 1H_2.L 2H.L 0很好 1一般
result=result[[“1H.L”,“1H_2.L”]]
解决了你的问题吗?没有,因为我想写出所有四列,但我只想去掉其中两列的大括号。我可以用我正在阅读的文件中的一个样本来更新我的答案是你想要的吗?@Bharathshetty嗨,谢谢你,但这并不是我想要问的。我更新了我的问题。
result=result[[“1H.L”,“1H_2.L”]]
解决了你的问题吗?没有,因为我想写出所有四列,但我只想去掉其中两列的大括号。我可以用我正在阅读的文件中的一个样本来更新我的答案是你想要的吗?@Bharathshetty嗨,谢谢你,但这并不是我想要问的。我更新了我的问题。