![](/img/trans.png)
[英]How can I manipulate python list and convert it to pandas dataframe?
[英]How can I convert list of string to pandas DataFrame in Python
我有包含這樣數據的.txt 文件。 第一個元素是用空格分隔的列名,下一個元素是數據。
['n Au[%] Ag[%] Cu[%] Zn[%] Ni[%] Pd[%] Fe[%] Cd[%] mq[ ]',
'1 71.085 4.6578 22.468 1.6971 0.0292 0.0000 0.0627 0.0000 1.1019',
'2 71.444 4.0611 22.946 1.4333 0.0400 0.0000 0.0763 0.0000 1.1298',
'3 71.845 4.2909 22.308 1.4234 0.0293 0.0000 0.1031 0.0000 1.0750',
'4 71.842 4.2794 22.290 1.4686 0.0339 0.0000 0.0856 0.0000 1.1334']
如何將此文本列表轉換為 Pandas DataFrame?
最簡單的解決方案是使用pandas.read_csv()
和delim_whitespace
選項:-)
輸入文件data.txt
n Au[%] Ag[%] Cu[%] Zn[%] Ni[%] Pd[%] Fe[%] Cd[%] mq[ ]
1 71.085 4.6578 22.468 1.6971 0.0292 0.0000 0.0627 0.0000 1.1019
2 71.444 4.0611 22.946 1.4333 0.0400 0.0000 0.0763 0.0000 1.1298
3 71.845 4.2909 22.308 1.4234 0.0293 0.0000 0.1031 0.0000 1.0750
4 71.842 4.2794 22.290 1.4686 0.0339 0.0000 0.0856 0.0000 1.1334
加工
import pandas as pd
file = "/path/to/file"
df = pd.read_csv(file, delim_whitespace=True)
Output
n Au[%] Ag[%] Cu[%] Zn[%] Ni[%] Pd[%] Fe[%] Cd[%] mq[ ]
0 1 71.085 4.6578 22.468 1.6971 0.0292 0.0 0.0627 0.0 1.1019 NaN
1 2 71.444 4.0611 22.946 1.4333 0.0400 0.0 0.0763 0.0 1.1298 NaN
2 3 71.845 4.2909 22.308 1.4234 0.0293 0.0 0.1031 0.0 1.0750 NaN
3 4 71.842 4.2794 22.290 1.4686 0.0339 0.0 0.0856 0.0 1.1334 NaN
根據您提供的信息,我編寫了幾行基本的 Python 代碼。
# Import needed dependencies
import pandas as pd
以下是您的數據,如上所示。 我保留了它的原始格式,但為了保持一致性,在最后一列值中添加了“%”。
mylist = [
'n Au[%] Ag[%] Cu[%] Zn[%] Ni[%] Pd[%] Fe[%] Cd[%] mq[%]',
'1 71.085 4.6578 22.468 1.6971 0.0292 0.0000 0.0627 0.0000 1.1019',
'2 71.444 4.0611 22.946 1.4333 0.0400 0.0000 0.0763 0.0000 1.1298',
'3 71.845 4.2909 22.308 1.4234 0.0293 0.0000 0.1031 0.0000 1.0750',
'4 71.842 4.2794 22.290 1.4686 0.0339 0.0000 0.0856 0.0000 1.1334'
]
提取第一個列表元素,因為它包含將成為列值的值。
# Extract the column values from the first row
col_values = mylist[0]
col_values = col_values.split()
del col_values[0]
獲取每個列表元素並將其分解為字符串組件並刪除第一個元素。
# Loop through each row of the file.
a_list = []
for row in mylist[1:]:
row_values = row
row_values = row_values.split()
del row_values[0]
a_list.append(row_values)
將所有列值收集到一個名為 main_list 的主列表中。
# Count variable
count = 0
main_list = []
for col in col_values:
temp_list = []
for _list in a_list:
temp_list.append(_list[count])
main_list.append(temp_list)
count += 1
現在讓我們創建一個字典並用它來生成 dataframe。
my_dct = {}
# Create custom dictionary based on dim's of main_list
for iteration in range(len(main_list)):
my_dct.update({col_values[iteration]:main_list[iteration]})
my_df = pd.DataFrame(dct)
希望您覺得這很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.