答案 0 :(得分:3)
简单回答:不要打扰删除行,但要插入新行,只选择你想要的内容。
看起来像这样:
# leave row alone, don't bother deleting columns in it.
new_row = ["a=%s;b=%s;c=%s;d=%s"% (row[12], row[13], row[14])]
# new_row has only one column, with a string constructed of what you need.
writer.writerow(new_row)
瞧,那应该为你做。您还可以将所需的任何其他列复制到new_row,并append()
复制您可能需要的任何其他列。
答案 1 :(得分:0)
答案 2 :(得分:0)
尝试pandas
import pandas as pd
df = pd.read_csv('1-0002.csv')
df['d_merged'] = df.apply(lambda row: 'a={0};b={1};c={2};d={3};'.format(row['a'],row['b'],row['c'],row['d']), axis=1)
这给出了:
>>> df
a b c d d_merged
0 1 2 3 4 a=1;b=2;c=3;d=4;
1 1 2 3 4 a=1;b=2;c=3;d=4;
2 1 2 3 4 a=1;b=2;c=3;d=4;
现在删除您不想要的列:
df = df.drop(['a','b','c','d'], axis=1)
>>> df
d_merged
0 a=1;b=2;c=3;d=4;
1 a=1;b=2;c=3;d=4;
2 a=1;b=2;c=3;d=4;
如果您愿意,现在重命名d_merged
:
df = df.rename(columns={'d_merged':'d'})
>>> df
d
0 a=1;b=2;c=3;d=4;
1 a=1;b=2;c=3;d=4;
2 a=1;b=2;c=3;d=4;
(或者,将上述两个步骤合并为:
df['d'] = df.apply(lambda row: 'a={0};b={1};c={2};d={3};'.format(row['a'],row['b'],row['c'],row['d']), axis=1)
)
然后写入CSV:
df.to_csv('csvout.csv', index=False)