Skip to main content
 首页 » 编程设计

python之使用 Pandas 将一行中的所有单元格值转换为字符串

2024年11月01日21yjmyzz

我在 csv 文件中有以下行,我想将所有单元格值连接在一行中并将它们转换为字符串。

输入:

      A      B    C    D    E   
A   hello  Alan  How  are  you  

输出:你好艾伦你好吗

这是我现在拥有的:

df = pd.read_csv(input_file) 
output = [''.join(str(df.values[:,i])) for i in range(len(df.values))] 

异常(exception):

IndexError: index 8 is out of bounds for axis 1 with size 8 

如有任何帮助,我们将不胜感激。

请您参考如下方法:

如果只需要处理一行,请使用 DataFrame.iloc 按位置选择它或 DataFrame.loc并添加 join:

output = ' '.join(df.iloc[0]) 

output = ' '.join(df.loc['A']) 
 
print (output) 
hello Alan How are you 

处理所有行:

s = df.apply(' '.join, 1)