如何将 Pandas 数据帧行转换为逗号分隔的字符串 [英] How to turn a pandas dataframe row into a comma separated string

查看:110
本文介绍了如何将 Pandas 数据帧行转换为逗号分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历 pandas df 的每一行并将其转换为逗号分隔的字符串.

I need to iterate over each row of a pandas df and turn this into a comma separated string.

示例:

df3 = DataFrame(np.random.randn(10, 5),
              columns=['a', 'b', 'c', 'd', 'e'])


          a         b         c         d         e
0 -0.158897 -0.749799  0.268921  0.070035  0.099600
1 -0.863654 -0.086814 -0.614562 -1.678850  0.980292
2 -0.098168  0.710652 -0.456274 -0.373153 -0.533463
3  1.001634 -0.736187 -0.812034  0.223062 -1.337972
4  0.173549 -0.576412 -1.016063 -0.217242  0.443794
5  0.273695  0.335562  0.778393 -0.668368  0.438880
6 -0.783824  1.439888  1.057639 -1.825481 -0.770953
7 -1.025004  0.155974  0.645023  0.993379 -0.812133
8  0.953448 -1.355628 -1.918317 -0.966472 -0.618744
9 -0.479297  0.295150 -0.294449  0.679416 -1.813078

我想为每一行获取:

 '-0.158897,-0.749799,0.268921,0.070035,0.099600'
 '0.863654,-0.086814,-0.614562,-1.678850,0.980292'
... and so on

推荐答案

你可以使用 pandas.DataFrame.to_string 将一些可选参数设置为 False 然后拆分换行符以获取字符串列表.不过这感觉有点脏.

You could use pandas.DataFrame.to_string with some optional arguments set to False and then split on newline characters to get a list of your strings. This feels a little dirty though.

x = df3.to_string(header=False,
                  index=False,
                  index_names=False).split('\n')
vals = [','.join(ele.split()) for ele in x]
print(vals)

输出:

<代码> [ '1.221365,0.923175,-1.286149,-0.153414,-0.005078', '-0.231824,-1.131186,0.853728,0.160349,1.000170', '-0.147145,0.310587,-0.388535,0.957730,-0.185315''-1.658463,-1.114204,0.760424,-1.504126,0.206909', '-0.734571,0.908569,-0.698583,-0.692417,-0.768087', '0.000029,0.204140,-0.483123,-1.064851,-0.835931',-0.108869,0.426260,0.107286,-1.184402,0.434607' , '-0.692160,-0.376433,0.567188,-0.171867,-0.822502', '-0.564726,-1.084698,-1.065283,-2.335092,-0.083357',-1.429049,0.790535,-0.547701,-0.684346,2.048081']

这篇关于如何将 Pandas 数据帧行转换为逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆