这是我的CSV:
AAP,AAMC,AAPL,AMT
106.08999633789062,,,
,122.88999938964844,,
,,109.80000305175781,
,,,118.55000305175781
由于所有的','和换行符,我的第二行被打印在楼梯上。如何使用python获取同一行缩进的所有数据?
我尝试使用.replace函数,但是每次都需要进行硬编码。有没有办法找到模式以便于:
因此预期输出如下:
AAP,AAMC,AAPL,AMT
106.08999633789062,122.88999938964844,109.80000305175781,118.55000305175781
答案 0 :(得分:0)
尝试一下:
import csv
data = {}
with open('input.txt') as input_file:
reader = csv.DictReader(input_file, delimiter=',')
for row in reader:
for key, value in row.items():
if value:
data[key] = value
with open('output.txt', 'w', newline='') as output_file:
writer = csv.DictWriter(output_file, delimiter=',', fieldnames=data.keys())
writer.writeheader()
writer.writerow(data)
数据是:
{'AAMC': '122.88999938964844',
'AAP': '106.08999633789062',
'AAPL': '109.80000305175781',
'AMT': '118.55000305175781'}
Output.txt:
AAP,AAMC,AAPL,AMT
106.08999633789062,122.88999938964844,109.80000305175781,118.55000305175781
答案 1 :(得分:0)
这里是一种方法:
import pandas as pd
df = pd.read_csv('a.csv')
m = df.max()
print(list(m.keys())); print(list(m.values))
# => ['AAP', 'AAMC', 'AAPL', 'AMT']
# => [106.08999633789062, 122.88999938964844, 109.8000030517578, 118.5500030517578]
答案 2 :(得分:0)
您可以尝试以下代码:
import pandas as pd
df=pd.read_csv("a.csv",delimeter=',',skipinitialspace=True,delim_whitespace=True)
print(list(df.keys()))
print(list(df.values()))
df.to_csv("b.csv",index=False)