python - 根据列条件从单个 DataFrame 创建多个 DataFrame
问题描述
pandas 和 python 的新手,所以提前谢谢你。我有一张桌子
# Create DataFrame
data = [{'analyte': 'sample1'},
{'analyte': 'bacon', 'CAS1': 1},
{'analyte': 'eggs', 'CAS1': 2},
{'analyte': 'money', 'CAS1': 3, 'CAS2': 1, 'Value2': 1.11},
{'analyte': 'shoe', 'CAS1': 4},
{'analyte': 'boy', 'CAS1': 5},
{'analyte': 'girl', 'CAS1': 6},
{'analyte': 'onion', 'CAS1': 7, 'CAS2': 4, 'Value2': 6.53},
{'analyte': 'sample2'},
{'analyte': 'bacon', 'CAS1': 1},
{'analyte': 'eggs', 'CAS1': 2, 'CAS2': 1, 'Value2': 7.88},
{'analyte': 'money', 'CAS1': 3},
{'analyte': 'shoe', 'CAS1': 4, 'CAS2': 3, 'Value2': 15.5},
{'analyte': 'boy', 'CAS1': 5},
{'analyte': 'girl', 'CAS1': 6},
{'analyte': 'onion', 'CAS1': 7}]
df = pd.DataFrame(data)
在将 Pandas DataFrame 写入 MySQL 数据库表之前,我需要将 df 拆分为单独的表,然后将每个表写入 Mysql
如何按列拆分 df,有些人认为,如果列名包含字符串“cas1”,则拆分 df
for col in df.columns:
if "cas1" in col:
dfCas1 = df.split
#add uniq index to indetify to which row belongs to
if "cas2" in col:
dfCas2 = df.split
#add uniq index to indetify to which row belongs to
if {"analyte","id" .etc } in col: # main table
dfMain = df.split
dfMain.to_sql("Main", dbConnection, if_exists='fail')
dfCas1.to_sql("cas1", dbConnection, if_exists='fail')
dfCas2.to_sql("cas2", dbConnection, if_exists='fail')
解决方案
我不是 100% 确定这是否是您的意思,但是:
dfCas1 = df[df.col.str.contains('cas1')]
dfCas2 = df[df.col.str.contains('cas2')]
dfMain = df[~((df.col.str.contains('cas2')) & df.col.str.contains('cas1'))]
~ 符号否定选择并表示列不包含 cas1 和 cas2 的所有行。我希望这是有道理的。
推荐阅读
- bootstrap-4 - 在 Microsoft Edge 上,Bootstrap 4 Card cut(使用 Shuffle.js 通过 ajax 调用加载)工作正常
- sdk - 如果已安装 .NET Core SDK,是否需要安装 .NET Core 运行时?
- javascript - JavaScript 中没有赋值的对象返回
- html - 如何在 CSS 中执行线性闪避?
- php - php按位并返回错误结果
- r - 在 R 中解析 SVG 路径
- python - How to compute derivatives with Lambdify and IndexedBase in sympy
- c++ - float f = 1.25 's hex value in visual studio 2017, win 10
- ms-access - 根据另一个文本框填充文本框值 - Ms Access
- automation - 用于重命名和处理电子邮件的 Mac OS 文件夹操作