[英]Reading lines from file and assigning content to variables
我有一個包含很多行的文件。 每條線的長度相同。
前三行是:
0 MSG_201901010100.nc [98.22227, 0.00014308207] [3948.8948, 0.0057524233]
1 MSG_201901010200.nc [197.27554, 0.00028737469] [9986.71, 0.014547813]
2 MSG_201901010300.nc [218.46107, 0.00031823604] [12044.043, 0.017544765]
如何讀取文件並將內容分配給列表,arrays 或 Dataframe?
作為列表,我想要:
a = [0,1,2]
b = [R10CH20P_MSG_201901010100.nc, R10CH20P_MSG_201901010200.nc, R10CH20P_MSG_201901010300.nc]
c1 = [98.22227, 197.27554, 218.46107]
c2 = [0.00014308207, 0.00028737469,0.00031823604]
d1 = [3948.8948, 9986.71, 12044.043]
d2 = [0.0057524233, 0.014547813, 0.017544765]
我試圖用 Pandas 讀取文件:
import pandas as pd
df = pd.read_table(filename, sep='\s+', names=['a', 'b', 'c1', 'c2', 'd1', 'd2' ])
但這會產生錯誤的分配:
print(df)
a b c1 c2 d1 d2
0 0 MSG_201901010100.nc [98.22227, 0.00014308207] [3948.8948, 0.0057524233]
1 1 MSG_201901010200.nc [197.27554, 0.00028737469] [9986.71, 0.014547813]
2 2 MSG_201901010300.nc [218.46107, 0.00031823604] [12044.043, 0.017544765]
例如print(df['c1']
) 給出:
0 [98.22227,
1 [197.27554,
2 [218.46107,
Name: c1, dtype: object
和
print(df['c1'].values)
顯示:
['[98.22227,' '[197.27554,' '[218.46107,']
這應該適用於您的用例,
with open('data.txt', 'r') as f:
lines = f.readlines()
data = []
for s in lines:
s = s.replace('[', '')
s = s.replace(']', '')
s = s.replace(',', '')
data.append(s.split())
df = pd.DataFrame(data=data, columns=['a', 'b', 'c1', 'c2', 'd1', 'd2'])
最后,
a = df['a'].tolist()
b= df['b'].tolist()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.