使用Python Pandas读取双列文本文件获取T、V值时遇阻求助
解决从文本文件中正确提取T、V值并迭代的问题
尝试从包含T、V两列的文本文件中读取所有行的T、V值,迭代后传递给其他函数,但遇到阻碍。
源文件内容:
T1|V1 T2|V2 T3|V3当前输出带有多余信息:
T1:1 V1 Name: T1, dtype: object T2:1 V2 Name: T1, dtype: object T3:1 V3 Name: T3, dtype: object当前代码:
import pandas as pd dfcsv = pd.read_csv("mycsv.txt" , delimiter = '|', header=None, index_col=0) df = pd.DataFrame(dfcsv) for t,v in df.iterrows(): T = str(t) V = str(v) print (T+":"+V)
问题原因
问题出在**index_col=0的设置**和对iterrows()返回值的处理上:
- 设置
index_col=0后,第一列(T列)被设为DataFrame的索引,剩下的V列是以Series形式存储的 iterrows()返回的v是一个Series对象,直接转字符串会输出整个Series的元数据(包括索引名、数据类型),而不是单纯的V值
方案1:不将T列设为索引(推荐)
读取时不指定index_col,直接给两列命名,这样可以更直观地提取T、V值:
import pandas as pd # 读取文件,指定列名为T和V df = pd.read_csv("mycsv.txt", delimiter='|', header=None, names=['T', 'V']) # 迭代每一行提取T、V for _, row in df.iterrows(): T = row['T'] V = row['V'] print(f"{T}:{V}") # 传递给其他函数:other_function(T, V)
如果追求更高的迭代效率,推荐使用itertuples():
import pandas as pd df = pd.read_csv("mycsv.txt", delimiter='|', header=None, names=['T', 'V']) for row in df.itertuples(index=False): T = row.T V = row.V print(f"{T}:{V}") # other_function(T, V)
方案2:保留索引并正确提取V值
如果必须保留T列为索引,只需提取Series中的具体值即可:
import pandas as pd df = pd.read_csv("mycsv.txt", delimiter='|', header=None, index_col=0) for t, v_series in df.iterrows(): T = str(t) # 提取Series中的唯一值(因为只有一列) V = str(v_series.iloc[0]) print(f"{T}:{V}") # other_function(T, V)
内容的提问来源于stack exchange,提问作者irnerd
相关产品推荐
相关产品推荐

