我有一个txt文件,其中包含信息,每次使用\ n符号分隔。
DEAL: 896
CITY: New York
MARKET: Manhattan
PRICE: $9,750,000
ASSET TYPE: Rental Building
SF: 8,004
PPSF: $1,218
DATE: 11/01/2017
是否可以用熊猫或csv模块制作带有标题的csv(或其他)表,如CITY,MARKET等。来自特定标题的所有信息都应放入相应的标题
答案 0 :(得分:1)
使用熊猫输入它,然后变换/旋转表。
import pandas as pd
df = pd.read_csv('data.txt',sep=':',header=None)
df = df.set_index(0).T
示例
import pandas as pd
data = '''
DEAL: 896
CITY: New York
MARKET: Manhattan
PRICE: $9,750,000
ASSET TYPE: Rental Building
SF: 8,004
PPSF: $1,218
DATE: 11/01/2017
'''
df = pd.read_csv(pd.compat.StringIO(data),sep=':',header=None)
print(df.set_index(0).T)
答案 1 :(得分:1)
已更新为使用:
作为分隔符来浏览:
import pandas as pd
new_temp = open('temp.txt', 'w') # writing data to a new file changing the first delimiter only
with open('fun.txt') as f:
for line in f:
line = line.replace(':', '|', 1) # only replace first instance of : to use this as delimiter for pandas
new_temp.write(line)
new_temp.close()
df = pd.read_csv('temp.txt', delimiter='|', header=None)
df = df.set_index([0]).T
df.to_csv('./new_transposed_df.csv', index=False)
将在不更改第二列冒号的情况下,将左列作为标题,右列作为数据创建一个csv。它将写出一个名为temp.txt的临时文件,您可以在运行该程序后将其删除。