简体   繁体   English

python-通过在每行中添加字符来编辑csv

[英]python - editing csv by adding chars to each row

I've got this dataset in a .csv file: https://www.dropbox.com/s/2kzpzkhoiolhnlc/output.csv?dl=0 我将此数据集保存在.csv文件中: https : //www.dropbox.com/s/2kzpzkhoiolhnlc/output.csv? dl =0

19,3,12
3
12
16,4
26,15,8,3
2
8
15
20
12,25,20,2,16
12,16
12,25
2,16
1,12
16,4
11,19,25,20
11,20,16,21
25,20,21
.....

for each row, if numbers are less then 51 than I need to add ? 对于每一行,如果数字小于51,而我需要添加? until having 51 chars in that row. 直到该行中有51个字符。 For example, in the first row I have 19,3,12, so I have to add 48 ? 例如,在第一行中,我有19、3、12,所以我必须添加48? to have a row like this: 19,3,12,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? 有这样一行: 19,3,12,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? In the second row I have just one number, so I have to add 50 ?, the same for the other rows. 在第二行中,我只有一个数字,所以我必须加50?,其他行也一样。 Could you help me please? 请问你能帮帮我吗?

EDIT: I've tried with this but didn't work, it just added "" to some rows: 编辑:我已经尝试过,但是没有用,它只是在一些行中添加了“”:

import pandas as pd
df = pd.read_csv('output.csv', sep=';')
df = df.fillna('?')
df.to_csv('sorted2.csv', index=False)

you can do it with just text file manipulation if you want, no need to use pandas or csv module for this simple case. 您可以仅通过文本文件操作即可完成此操作,这种简单情况无需使用pandas或csv模块。

import csv
with open('source.csv') as f:
    with open('result.csv', 'w') as fw:
        for line in f:
            line = line.strip() + (',?' * (50 - line.count(',')))
            fw.write(line + '\n')   

Use pandas to read the file in and set the number of columns you want. 使用熊猫读取文件并设置所需的列数。 The following code reads in a file and assigns n columns. 以下代码读取文件并分配n列。 The extra elements will by default have value np.nan 默认情况下,多余的元素的值为np.nan

df.read_csv('file', names=range(n))

If you want them to have a different value you can assign it with 如果您希望它们具有不同的值,则可以使用

df.fillna(value, inplace = True)

Then you can just write the dataframe back into the file and it will have the shape you want 然后,您只需将数据框写回到文件中,它将具有所需的形状

df.to_csv('file')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM