Pandas DataFrame 可以通过调用x.tolist() 转换为 Python 列表。你也可以使用list(x)
import pandas as pd
datadict = {'col1': [1, 1.5, 1.24], 'col2': [7, 6.7, 5.5], 'col3': [8, 9, 8.8]}
df = pd.DataFrame(datadict)
print(f"DataFrame:\n{df}")
# 1st way:
def func1(df_):
my_list = list()
for col in df_.columns:
my_list.append(df_[col].tolist())
return my_list
result1 = func1(df)
print(f"Using x.tolist():\n{result1}")
# 2nd way:
func2 = lambda df_: [list(df_[col]) for col in df_.columns]
result2 = func2(df)
print(f"Using list(x):\n{result2}")
输出:
DataFrame:
col1 col2 col3
0 1.00 7.0 8.0
1 1.50 6.7 9.0
2 1.24 5.5 8.8
Using x.tolist():
[[1.0, 1.5, 1.24], [7.0, 6.7, 5.5], [8.0, 9.0, 8.8]]
Using list(x):
[[1.0, 1.5, 1.24], [7.0, 6.7, 5.5], [8.0, 9.0, 8.8]]