我试图连接dataframes
streamlit 中以字符串开头的所有内容user_
,但出现了错误。
示例代码:
import streamlit as st
import pandas as pd
st.set_page_config(page_title="Science",
layout='wide',
initial_sidebar_state="expanded")
# sample dataframes
st.session_state.user_df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
st.session_state.user_df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})
st.session_state.df3 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
# list of dataframes starting with user_
st.session_state.users_list = [name for name in st.session_state if name.startswith('user_')]
st.write(st.session_state.users_list)
# using eval to evaluate string dataframe names
# st.write([eval(st.session_state.name) for st.session_state.name in st.session_state.users_list])
st.session_state.df_final = pd.concat([eval(st.session_state.name) for st.session_state.name
in st.session_state.users_list],
ignore_index=True)
st.table(st.session_state.df_final)
更新:
整个逻辑都可以正常工作,但我在streamlit中streamlit
遇到了错误,不知道哪里出了问题。非常感谢您的帮助!!
这种没有 streamlit 的逻辑/代码是可行的:
import pandas as pd
user_df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
user_df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})
df3 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
users_list = ['user_df1','user_df2']
print([eval(name) for name in users_list])
df_final = pd.concat([eval(name) for name in users_list],ignore_index=True)
print('----df_final------')
print(df_final)
输出:
[ A B
0 1 3
1 2 4, A B
0 5 7
1 6 8]
----df_final------
A B
0 1 3
1 2 4
2 5 7
3 6 8
``
eval
对 UPDATE 中的数据框进行评估,因为它可以在本地范围内访问。的值
st.session_state.users_list
是的属性st.session_state
,应该从对象中访问。我建议使用该
getattr
函数而不是 eval,因为它明确地显示了对象的属性被访问。