我正在尝试将一组pandas
数据帧转换为唯一列表,
到目前为止我得到的是:
import pandas as pd
df1= pd.DataFrame(data={'col1': [1, 2, 5], 'col2': [3, 4, 4]})
df2 = pd.DataFrame(data={'col3':[1,2,3,4,5], 'col4':[1,2,'NA', 'NA', 'NA'], 'col5':['John', 'Mary', 'Gordon', 'Cynthia', 'Marianne']})
df3 = pd.DataFrame(data={'col6':[19, 25,20, 23]})
#### attempt to convert into a list ####
df_list = list(df1, df2, df3)
错误:
TypeError: list期望最多1个参数,得到3个
预期的输出应该返回索引的数据帧名称作为列表的一个元素,像print(df_list['df1'])
将返回df1
列和行。
有办法完成这个任务吗?
不可能在python中使用list
的字符串索引。列表具有从0
到len(my_list)-1
的数字索引。
如果你要使用list()
调用本身,它需要一个iterable
变量:
>>> help(list)
class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items
你可以构造一个元组并把它传递给list()
类,比如:
>>> my_list = list((df1, df2, df3))
>>> type(my_list)
<class 'list'>
>>> my_list[0]
... df1 outputs here ...
但更简单、更清晰的方法是使用方括号符号:
>>> my_list = [df1, df2, df3]
>>> type(all_dataframes)
<class 'list'>
然而,如果你想使用字符串索引,那么考虑使用字典,即dict
类:
>>> help(dict)
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
| Methods defined here:
|
直接调用dict()
类,您需要这样做:
>>> all_dataframes = dict(("df1", df1), ("df2", df2), ("df3", df3))
>>> type(all_dataframes)
<class 'dict'>
>>> all_dataframes["df1"]
... df1 output prints here ...
但是,更简单、更清晰的方法是:
>>> all_dataframes = {"df1": df1, "df2": df2, "df3": df3}
>>> type(all_dataframes)
<class 'dict'>
这里使用list()
是不正确的,因为它没有将参数分组到一个列表中。你可以直接使用[]
:
df_list = [df1, df2, df3]
但是list
不能用名字索引,所以你可能想要一个dict
:
df_dict = {'df1':df1, 'df2':df2, 'df3':df3}
然后你可以做df_dict['df1']
。
请注意,您不能以编程方式使用变量名(df1
,df2
,df3
)来构造用于访问它们的字符串('df1'
,'df2'
,'df3'
)。