如何将行转换为两列,其中每个新行都从原始行的第一个字符串开始?
How to transform rows to two columns, where each new row begins with the first string of the original row?
我的 CSV 数据如下所示:
non alc,cola,fanta
alc,vodka,vine,beer
juice,apple,orange,tomato,cherry
这是一个示例 - 实际数据行要长得多,最大行长度约为 200 个字符串。
我想将所有数据转换为两列,其中转换数据的每一行都以原始行的第一个字符串开头。像这样:
non alc,cola
non alc,fanta
alc,vodka
alc,vine
alc,beer
juice,apple
juice,orange
juice,tomato
juice,cherry
用 Python 做这个的方法是什么?
如果这种转换有一个特殊的名字-我会很感激知道它。
您可以使用 pandas lib:
import pandas as pd
df = pd.read_fwf('in.txt', header=None)
df = df[0].str.split(',', 1, expand=True)
df[1] = df[1].str.split(',', expand=False)
df = df.explode([1])
df.to_csv('out.txt',index=False,header=None)
我不确定你是否想这样解决,但请检查我的答案。
<beverage.csv>
non alc,cola,fanta
alc,vodka,vine,beer
juice,apple,orange,tomato,cherry
Python代码:
import csv
file = open('./beverage.csv')
csv_reader = csv.reader(file)
for row in csv_reader:
for i in range(1, len(row)):
print(row[0] + ', ' + row[i])
file.close()
结果:
non alc, cola
non alc, fanta
alc, vodka
alc, vine
alc, beer
juice, apple
juice, orange
juice, tomato
juice, cherry
我的 CSV 数据如下所示:
non alc,cola,fanta
alc,vodka,vine,beer
juice,apple,orange,tomato,cherry
这是一个示例 - 实际数据行要长得多,最大行长度约为 200 个字符串。
我想将所有数据转换为两列,其中转换数据的每一行都以原始行的第一个字符串开头。像这样:
non alc,cola
non alc,fanta
alc,vodka
alc,vine
alc,beer
juice,apple
juice,orange
juice,tomato
juice,cherry
用 Python 做这个的方法是什么?
如果这种转换有一个特殊的名字-我会很感激知道它。
您可以使用 pandas lib:
import pandas as pd
df = pd.read_fwf('in.txt', header=None)
df = df[0].str.split(',', 1, expand=True)
df[1] = df[1].str.split(',', expand=False)
df = df.explode([1])
df.to_csv('out.txt',index=False,header=None)
我不确定你是否想这样解决,但请检查我的答案。
<beverage.csv>
non alc,cola,fanta
alc,vodka,vine,beer
juice,apple,orange,tomato,cherry
Python代码:
import csv
file = open('./beverage.csv')
csv_reader = csv.reader(file)
for row in csv_reader:
for i in range(1, len(row)):
print(row[0] + ', ' + row[i])
file.close()
结果:
non alc, cola
non alc, fanta
alc, vodka
alc, vine
alc, beer
juice, apple
juice, orange
juice, tomato
juice, cherry