3 回答

TA貢獻(xiàn)1794條經(jīng)驗 獲得超8個贊
一些正則表達(dá)式來提取細(xì)節(jié),然后向前填充前兩列并刪除空值
pattern = r"(?P<Date>\d{2}/\d{2}/\d{4})|(?P<Description>[a-z]+)|(?P<Amount>\d{1,}\.00)"
res = (df1.text.str.extract(pattern)
.assign(Date = lambda x: x.Date.ffill(),
Description = lambda x: x.Description.ffill()
)
.dropna(how='any')
)
res
Date Description Amount
2 10/21/2019 abcdef 100.00
5 10/22/2019 ghijk 120.00
如果你不關(guān)心正則表達(dá)式,并且格式是不變的,那么我們可以用 numpy 重塑數(shù)據(jù)并創(chuàng)建一個新的數(shù)據(jù)框。
#reshape the data
#thanks to @Chester
#removes unnecessary computation
res = np.reshape(df1.to_numpy(),(-1,3))
#create new dataframe
pd.DataFrame(res,columns=['Date','Description','Amount'])
Date Description Amount
0 10/21/2019 abcdef 100.00
1 10/22/2019 ghijk 120.00

TA貢獻(xiàn)1852條經(jīng)驗 獲得超1個贊
將原始數(shù)據(jù)從文件讀取到 aSeries
并轉(zhuǎn)換為PandasArray
以簡化以后對索引的處理:
raw_data = pd.read_csv("path\to\a\data\file.txt", names=['raw_data'], squeeze=True).array
創(chuàng)建一個DataFrame
使用切片:
df = pd.DataFrame(data={'Data': raw_data[::3], 'Description': raw_data[1::3], 'Amount': raw_data[2::3]})
只需 2 個簡單的步驟,無需正則表達(dá)式和不必要的轉(zhuǎn)換。簡短高效。

TA貢獻(xiàn)1802條經(jīng)驗 獲得超5個贊
如果您的字符串具有您提到的確切模式,則可以使用以下代碼
string = '''10/21/2019
abcdef
100.00
10/22/2019
ghijk
120.00'''
token_list = string.split()
Data = token_list[0::3]
Description = token_list[1::3]
Amount = token_list[2::3]
Aggregate = list(zip(Data, Description, Amount))
df = pd.DataFrame(Aggregate, columns = ['Data ', 'Description', 'Amount'])
添加回答
舉報