我有以下格式的檔案:
標題 1
這里有一些文字
標題 2
這里有一些文字
標題 3
這里有一些文字
我需要創建一個格式的資料框
df=
| 標題 | 文本 |
|---|---|
| 標題 1 | 這里有一些文字 |
| 標題 2 | 這里有一些文字 |
| 標題 3 | 這里有一些文字 |
uj5u.com熱心網友回復:
你可以試試下面的代碼:
with open('data.txt') as fp:
data = [line.strip() for line in fp if line.strip()]
df = pd.DataFrame(list(zip(data[::2], data[1::2])), columns=['Heading', 'text'])
輸出:
>>> df
Heading text
0 Heading 1 Some text here
1 Heading 2 Some text here
2 Heading 3 Some text here
data.txt檔案內容:
Heading 1
Some text here
Heading 2
Some text here
Heading 3
Some text here
uj5u.com熱心網友回復:
考慮到檔案的Header在奇數行和text在偶數行:
您首先讀取整個資料并創建一個numpy陣列。然后你可以將它重塑為nx2. 最后但并非最不重要的是,您可以從中創建一個資料框。
import numpy as np
import pandas as pd
with open("data.dat", "r") as the_file:
data = np.array([d.strip() for d in the_file])
df = pd.DataFrame(data.reshape((-1, 2)), columns=["Heading", "text"])
uj5u.com熱心網友回復:
如果您想了解構建代碼的方式,可以修改以下內容。
df= DataFrame()
header=[]
text=[]
with open("sample.txt", "r") as f:
for f_line in f.readlines():
if f_line.startswith("Header"):
header.append(f_line.rstrip())
else:
text.append(f_line.rstrip())
df['header']=header
df['text']=text
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/353676.html
