python CSV writer, pandas , How to write the csv file in two column using the same text file has only one coulmn

huangapple go评论61阅读模式
英文:

python CSV writer, pandas , How to write the csv file in two column using the same text file has only one coulmn

问题

假设文本文件包含以下元素

    A
    B
    C
    D 

我想使用Python将这些元素写入CSV文件如下所示

    A,A
    A,B
    A,C
    A,D
    B,A
    B,B
    B,C
    B,D
    ...

我尝试使用以下代码将文本写入带有复制数据的CSV中

```python
import csv

with open(r'C:\Users\soso-\Desktop\SVM\DataSet\drug_list.txt') as f:
    with open('integrated_x.csv', 'w') as out_file:
        for line in f:
            for x in range(548):
                out_file.write(f"{line.strip()}\n")
f.close()
out_file.close()

输出:

A
A
A
A
B
B
B
...

然后在另一个CSV文件中为CSV文件添加新列,如下所示:

with open(r'C:\Users\soso-\Desktop\SVM\DataSet\drug_list.txt') as f:
    with open(r'integrated_x.csv') as read_obj, \
            open('integrated_x12.csv', 'w', newline='') as write_obj:
        # 从输入文件对象创建csv.reader对象
        csv_reader = csv.reader(read_obj)
        # 从输出文件对象创建csv.writer对象
        csv_writer = csv.writer(write_obj)

        # 将输入csv文件的每一行读取为列表
        for row in csv_reader:
            for line in f:
                # 将默认文本附加到行/列表中
                row.append(line.strip())
                # 将更新后的行/列表添加到输出文件
                csv_writer.writerow(row)

输出:

A,"A"
A,"A,B"
A,"A,B,C"

所以输出不如预期,它将列附加为列表并复制上一行。如何修复它?


<details>
<summary>英文:</summary>

suppose the text file contain these elements as follows:

    A
    B
    C
    D 

I want to write these elements in the CSV file using python as follows:

    A,A
    A,B
    A,C
    A,D
    B,A
    B,B
    B,C
    B,D
    ...

I try to write the text in csv with multiplicated data like this:

    import csv
    
    with open(r&#39;C:\Users\soso-\Desktop\SVM\DataSet\drug_list.txt&#39;) as f:
        with open(&#39;integrated_x.csv&#39;, &#39;w&#39;) as out_file:
            for line in f:
                for x in range(548):
                    out_file.write(f&quot;{line.strip()}\n&quot;)
    f.close()
    out_file.close()

output:

    A
    A
    A
    A
    B
    B
    B
    ....


Then add the new column for the csv file in the other csv file like this:

    with open(r&#39;C:\Users\soso-\Desktop\SVM\DataSet\drug_list.txt&#39;) as f:
        with open(r&#39;integrated_x.csv&#39;) as read_obj, \
                open(&#39;integrated_x12.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as write_obj:
        # Create a csv.reader object from the input file object
                    csv_reader = csv.reader(read_obj)
        # Create a csv.writer object from the output file object
                    csv_writer = csv.writer(write_obj)
            
        # Read each row of the input csv file as list
                    for row in csv_reader:
                        for line in f:
            # Append the default text in the row / list
                            row.append(line)
            # Add the updated row / list to the output file
                            csv_writer.writerow(row)

output:

    A,&quot;A&quot;
    A,&quot;A,B&quot;
    A,&quot;A,B,C&quot;

So the output not as expected it append the column as list and replicate the previous row.
How can I fix it?



</details>


# 答案1
**得分**: 0

使用标准库中的itertools.permutations:

```python
import itertools
list(itertools.permutations(['A', 'B', 'C', 'D'], 2))

如果要将其保存为CSV文件,可以使用pandas:

import pandas as pd
import itertools
a = list(itertools.permutations(['A', 'B', 'C', 'D'], 2))
df = pd.DataFrame(list(itertools.permutations(['A', 'B', 'C', 'D'], 2)))
df.to_csv('my_file.csv')

这是创建这种排列的最简单方式。

英文:

Use itertools.permutations from the standard library:

import itertools
list(itertools.permutations([&#39;A&#39;, &#39;B&#39;, &#39;C&#39; ,&#39;D&#39;], 2))


[(&#39;A&#39;, &#39;B&#39;), (&#39;A&#39;, &#39;C&#39;), (&#39;A&#39;, &#39;D&#39;), (&#39;B&#39;, &#39;A&#39;), (&#39;B&#39;, &#39;C&#39;), (&#39;B&#39;, &#39;D&#39;), (&#39;C&#39;, &#39;A&#39;), (&#39;C&#39;, &#39;B&#39;), (&#39;C&#39;, &#39;D&#39;), (&#39;D&#39;, &#39;A&#39;), (&#39;D&#39;, &#39;B&#39;), (&#39;D&#39;, &#39;C&#39;)]

If you want to save it as a csv file, then by pandas:

&gt;&gt;&gt; import pandas as pd
&gt;&gt;&gt; import itertools
&gt;&gt;&gt; a = list(itertools.permutations([&#39;A&#39;, &#39;B&#39;, &#39;C&#39; ,&#39;D&#39;], 2))
&gt;&gt;&gt; df = pd.DataFrame(list(itertools.permutations([&#39;A&#39;, &#39;B&#39;, &#39;C&#39; ,&#39;D&#39;], 2)))
&gt;&gt;&gt; df
    0  1
0   A  B
1   A  C
2   A  D
3   B  A
4   B  C
5   B  D
6   C  A
7   C  B
8   C  D
9   D  A
10  D  B
11  D  C
&gt;&gt;&gt; df.to_csv(&#39;my_file.csv&#39;)

This is easiest way to create this permutation

huangapple
  • 本文由 发表于 2023年2月8日 17:26:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定