如何将动态生成的 pandas 数据帧作为列值存储为.csv文件 [英] How to save pandas dataframe generated dynmically as column values as .csv file

查看:120
本文介绍了如何将动态生成的 pandas 数据帧作为列值存储为.csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据帧,它有一个Id列标题和值,现在我想生成新的列值,使用索引长度连接下划线和预定义常数,这将随着索引的增加而增加。例如,如果有3个索引。该值应为1_1,1_2和2_1等等。

  dfm = pd.DataFrame({'Id':[4,9,7,8,3,1]}) 
l = len(dfm.index)
def gen(l):
lst = []
for i in range(1,l + 1):
for j in range(1,7):
z ={} {} {}。format(i,'_',j)
lst.append((z))
return lst

>>> k = gen(l)
>>>> k
['1_1','1_2','1_3','1_4','1_5','1_6','2_1','2_2','2_3','2_4' '2_6','4_','4_','4_4','4_5','4_6','3' '5_1','5_2','5_3','5_4','5_5','5_6','6_1','6_2','6_3','6_4','6_5','6_6'
results =d:\\Id.csv
gf = pd.DataFrame({'Id':[gen(l)]})
gf.to_csv(results, index = False)

上述代码导致将结果保存为Id头,但值保存为不垂直列列。它被保存为1_1...,2_1。我想保存以上的结果,而不用引号

  result 
Id
1_1
1_2
1_3
1_4
...
2_1


解决方案

这解决了我的问题:

  gf = pd。 DataFrame({'Id':gen(l)})
gf.to_csv(results,index = False)


I have a pandas dataframe and it has an Id column header with values, now I want to generate new column values using the index length concatenating underscore and predefined constant which would increase as the index increases. For example if the there are 3 indexes. The value should be 1_1,1_2 and 2_1 and so on.

dfm = pd.DataFrame({'Id' : [4,9,7,8,3,1]})
l=len(dfm.index)
def gen(l):
  lst=[]
  for i in range(1,l+1):
    for j in range(1,7):
      z="{}{}{}".format(i,'_', j)
      lst.append((z))
  return lst

>>> k=gen(l)
>>> k
['1_1', '1_2', '1_3', '1_4', '1_5', '1_6', '2_1', '2_2', '2_3', '2_4', '2_5', '2_6', '3_1', '3_2', '3_3', '3_4', '3_5', '3_6', '4_1', '4_2', '4_3', '4_4', '4_5', '4_6', '5_1', '5_2', '5_3', '5_4', '5_5', '5_6', '6_1', '6_2', '6_3', '6_4', '6_5', '6_6']
results ="d:\\Id.csv"
gf = pd.DataFrame({'Id' : [gen(l)]})
gf.to_csv(results, index=False)  

The above code results in saving the result as Id header but the values are saved horizontally not vertically as column values. And it is saved as '1_1'... ,'2_1' so on . I want to save k in the above as result below without the quotations

result
      Id
      1_1
      1_2
      1_3
      1_4
      ...
      2_1

解决方案

This solved the problem for me:

gf = pd.DataFrame({'Id' : gen(l)})  
gf.to_csv(results, index=False)

这篇关于如何将动态生成的 pandas 数据帧作为列值存储为.csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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