编程开发

Dataverse转pandas

用PandasODataClient将查询结果转为DataFrame,便于清洗、分析和建模。

# Dataverse SDK for Python - Pandas 集成指南

## 概述
本指南介绍如何将 Dataverse SDK for Python 与 pandas DataFrame 集成,用于数据科学和分析工作流。该 SDK 的 JSON 响应格式可无缝映射到 pandas DataFrame,使数据科学家能够使用熟悉的数据处理工具处理 Dataverse 数据。

---

## 1. PandasODataClient 简介

### 什么是 PandasODataClient?
`PandasODataClient` 是标准 `DataverseClient` 的轻量封装,以 pandas DataFrame 格式而非原始 JSON 字典返回数据。这使它非常适合:
- 处理表格数据的数据科学家
- 分析和报告工作流
- 数据探索和清洗
- 与机器学习流水线集成

### 安装要求
```bash
# Install core dependencies
pip install PowerPlatform-Dataverse-Client
pip install azure-identity

# Install pandas for data manipulation
pip install pandas
```

### 何时使用 PandasODataClient
✅ **在需要以下功能时使用:**
- 数据探索和分析
- 处理表格数据
- 与统计或机器学习库集成
- 高效处理数据

❌ **在需要以下功能时改用 DataverseClient:**
- 仅执行实时 CRUD 操作
- 文件上传操作
- 元数据操作
- 单条记录操作

---

## 2. 基本 DataFrame 工作流

### 将查询结果转换为 DataFrame
```python
from azure.identity import InteractiveBrowserCredential
from PowerPlatform.Dataverse.client import DataverseClient
import pandas as pd

# Setup authentication
base_url = "https://<myorg>.crm.dynamics.com"
credential = InteractiveBrowserCredential()
client = DataverseClient(base_url=base_url, credential=credential)

# Query data
pages = client.get(
    "account",
    select=["accountid", "name", "creditlimit", "telephone1"],
    filter="statecode eq 0",
    orderby=["name"]
)

# Collect all pages into one DataFrame
all_records = []
for page in pages:
    all_records.extend(page)

# Convert to DataFrame
df = pd.DataFrame(all_records)

# Display first few rows
print(df.head())
print(f"Total records: {len(df)}")
```

### 查询参数映射到 DataFrame
```python
# All query parameters return as columns in DataFrame
df = pd.DataFrame(
    client.get(
        "account",
        select=["accountid", "name", "creditlimit", "telephone1", "createdon"],
        filter="creditlimit > 50000",
        orderby=["creditlimit desc"]
    )
)

# Result is a DataFrame with columns:
# accountid | name | creditlimit | telephone1 | createdon
```

---

## 3. 使用 Pandas 进行数据探索

### 基本探索
```python
import pandas as pd
from azure.identity import InteractiveBrowserCredential
from PowerPlatform.Dataverse.client import DataverseClient

client = DataverseClient("https://<myorg>.crm.dynamics.com", InteractiveBrowserCredential())

# Load account data
records = []
for page in client.get("account", select=["accountid", "name", "creditlimit", "industrycode"]):
    records.extend(page)

df = pd.DataFrame(records)

# Explore the data
print(df.shape)           # (1000, 4)
print(df.dtypes)          # Data types
print(df.describe())      # Statistical summary
print(df.info())          # Column info and null counts
print(df.head(10))        # First 10 rows
```

### 筛选和选择
```python
# Filter rows by condition
high_value = df[df['creditlimit'] > 100000]

# Select specific columns
names_limits = df[['name', 'creditlimit']]

# Multiple conditions
filtered = df[(df['creditlimit'] > 50000) & (df['industrycode'] == 1)]

# Value counts
print(df['industrycode'].value_counts())
```

### 排序和分组
```python
# Sort by column
sorted_df = df.sort_values('creditlimit', ascending=False)

# Group by and aggregate
by_industry = df.groupby('industrycode').agg({
    'creditlimit': ['mean', 'sum', 'count'],
    'name': 'count'
})

# Group statistics
print(df.groupby('industrycode')['creditlimit'].describe())
```

### 数据清洗
```python
# Handle missing values
df_clean = df.dropna()                    # Remove rows with NaN
df_filled = df.fillna(0)                  # Fill NaN with 0
df_ffill = df.fillna(method='ffill')      # Forward fill

# Check for duplicates
duplicates = df[df.duplicated(['name'])]
df_unique = df.drop_duplicates()

# Data type conversion
df['creditlimit'] = pd.to_numeric(df['creditlimit'])
df['createdon'] = pd.to_datetime(df['createdon'])
```

---

## 4. 数据分析模式

### 聚合和汇总
```python
# Create summary report
summary = df.groupby('industrycode').agg({
    'accountid': 'count',
    'creditlimit': ['mean', 'min', 'max', 'sum'],
    'name': lambda x: ', '.join(x.head(3))  # Sample names
}).round(2)

print(summary)
```

### 时间序列分析
```python
# Convert to datetime
df['createdon'] = pd.to_datetime(df['createdon'])

# Resample to monthly
monthly = df.set_index('createdon').resample('M').size()

# Extract date components
df['year'] = df['createdon'].dt.year
df['month'] = df['createdon'].dt.month
df['day_of_week'] = df['createdon'].dt.day_name()
```

### 连接和合并操作
```python
# Load two related tables
accounts = pd.DataFrame(client.get("account", select=["accountid", "name"]))
contacts = pd.DataFrame(client.get("contact", select=["contactid", "parentcustomerid", "fullname"]))

# Merge on relationship
merged = accounts.merge(
    contacts,
    left_on='accountid',
    right_on='parentcustomerid',
    how='left'
)

print(merged.head())
```

### 统计分析
```python
# Correlation matrix
correlation = df[['creditlimit', 'industrycode']].corr()

# Distribution analysis
print(df['creditlimit'].describe())
print(df['creditlimit'].skew())
print(df['creditlimit'].kurtosis())

# Percentiles
print(df['creditlimit'].quantile([0.25, 0.5, 0.75]))
```

---

## 5. 数据透视表和报告

### 创建数据透视表
```python
# Pivot table by industry and status
pivot = pd.pivot_table(
    df,
    values='creditlimit',
    index='industrycode',
    columns='statecode',
    aggfunc=['sum', 'mean', 'count']
)

print(pivot)
```

### 生成报告
```python
# Sales report by industry
industry_report = df.groupby('industrycode').agg({
    'accountid': 'count',
    'creditlimit': 'sum',
    'name': 'first'
}).rename(columns={
    'accountid': 'Account Count',
    'creditlimit': 'Total Credit Limit',
    'name': 'Sample Account'
})

# Export to CSV
industry_report.to_csv('industry_report.csv')

# Export to Excel
industry_report.to_excel('industry_report.xlsx')
```

---

## 6. 数据可视化

### Matplotlib 集成
```python
import matplotlib.pyplot as plt

# Create visualizations
fig, axes = plt.subplots(2, 2, figsize=(12, 10))

# Histogram
df['creditlimit'].hist(bins=30, ax=axes[0, 0])
axes[0, 0].set_title('Credit Limit Distribution')

# Bar chart
df['industrycode'].value_counts().plot(kind='bar', ax=axes[0, 1])
axes[0, 1].set_title('Accounts by Industry')

# Box plot
df.boxplot(column='creditlimit', by='industrycode', ax=axes[1, 0])
axes[1, 0].set_title('Credit Limit by Industry')

# Scatter plot
df.plot.scatter(x='creditlimit', y='industrycode', ax=axes[1, 1])
axes[1, 1].set_title('Credit Limit vs Industry')

plt.tight_layout()
plt.show()
```

### Seaborn 集成
```python
import seaborn as sns

# Correlation heatmap
plt.figure(figsize=(8, 6))
sns.heatmap(df[['creditlimit', 'industrycode']].corr(), annot=True)
plt.title('Correlation Matrix')
plt.show()

# Distribution plot
sns.distplot(df['creditlimit'], kde=True)
plt.title('Credit Limit Distribution')
plt.show()
```

---

## 7. 机器学习集成

### 为机器学习准备数据
```python
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split

# Load and prepare data
records = []
for page in client.get("account", select=["accountid", "creditlimit", "industrycode", "statecode"]):
    records.extend(page)

df = pd.DataFrame(records)

# Feature engineering
df['log_creditlimit'] = np.log1p(df['creditlimit'])
df['industry_cat'] = pd.Categorical(df['industrycode']).codes

# Split features and target
X = df[['industrycode', 'log_creditlimit']]
y = df['statecode']

# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

print(f"Training set: {len(X_train)}, Test set: {len(X_test)}")
```

### 构建分类模型
```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

# Train model
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)

# Evaluate
y_pred = model.predict(X_test)
print(classification_report(y_test, y_pred))

# Feature importance
importances = pd.Series(
    model.feature_importances_,
    index=X.columns
).sort_values(ascending=False)

print(importances)
```

---

## 8. 高级 DataFrame 操作

### 自定义函数
```python
# Apply function to columns
df['name_length'] = df['name'].apply(len)

# Apply function to rows
df['category'] = df.apply(
    lambda row: 'High' if row['creditlimit'] > 100000 else 'Low',
    axis=1
)

# Conditional operations
df['adjusted_limit'] = df['creditlimit'].where(
    df['statecode'] == 0,
    df['creditlimit'] * 0.5
)
```

### 字符串操作
```python
# String methods
df['name_upper'] = df['name'].str.upper()
df['name_starts'] = df['name'].str.startswith('A')
df['name_contains'] = df['name'].str.contains('Inc')
df['name_split'] = df['name'].str.split(',').str[0]

# Replace and substitute
df['industry'] = df['industrycode'].map({
    1: 'Retail',
    2: 'Manufacturing',
    3: 'Technology'
})
```

### 重塑数据
```python
# Transpose
transposed = df.set_index('name').T

# Stack/Unstack
stacked = df.set_index(['name', 'industrycode'])['creditlimit'].unstack()

# Melt long format
melted = pd.melt(df, id_vars=['name'], var_name='metric', value_name='value')
```

---

## 9. 性能优化

### 高效加载数据
```python
# Load large datasets in chunks
all_records = []
chunk_size = 1000

for page in client.get(
    "account",
    select=["accountid", "name", "creditlimit"],
    top=10000,        # Limit total records
    page_size=chunk_size
):
    all_records.extend(page)
    if len(all_records) % 5000 == 0:
        print(f"Loaded {len(all_records)} records")

df = pd.DataFrame(all_records)
print(f"Total: {len(df)} records")
```

### 内存优化
```python
# Reduce memory usage
# Use categorical for repeated values
df['industrycode'] = df['industrycode'].astype('category')

# Use appropriate numeric types
df['creditlimit'] = pd.to_numeric(df['creditlimit'], downcast='float')

# Delete columns no longer needed
df = df.drop(columns=['unused_col1', 'unused_col2'])

# Check memory usage
print(df.memory_usage(deep=True).sum() / 1024**2, "MB")
```

### 查询优化
```python
# Apply filters on server, not client
# ✅ GOOD: Filter on server
accounts = client.get(
    "account",
    filter="creditlimit > 50000",  # Server-side filter
    select=["accountid", "name", "creditlimit"]
)

# ❌ BAD: Load all, filter locally
all_accounts = client.get("account")  # Loads everything
filtered = [a for a in all_accounts if a['creditlimit'] > 50000]  # Client-side
```

---

## 10. 完整示例:销售分析

```python
import pandas as pd
import numpy as np
from azure.identity import InteractiveBrowserCredential
from PowerPlatform.Dataverse.client import DataverseClient

# Setup
client = DataverseClient(
    "https://<myorg>.crm.dynamics.com",
    InteractiveBrowserCredential()
)

# Load data
print("Loading account data...")
records = []
for page in client.get(
    "account",
    select=["accountid", "name", "creditlimit", "industrycode", "statecode", "createdon"],
    orderby=["createdon"]
):
    records.extend(page)

df = pd.DataFrame(records)
df['createdon'] = pd.to_datetime(df['createdon'])

# Data cleaning
df = df.dropna()

# Feature engineering
df['year'] = df['createdon'].dt.year
df['month'] = df['createdon'].dt.month
df['year_month'] = df['createdon'].dt.to_period('M')

# Analysis
print("\n=== ACCOUNT OVERVIEW ===")
print(f"Total accounts: {len(df)}")
print(f"Total credit limit: ${df['creditlimit'].sum():,.2f}")
print(f"Average credit limit: ${df['creditlimit'].mean():,.2f}")

print("\n=== BY INDUSTRY ===")
industry_summary = df.groupby('industrycode').agg({
    'accountid': 'count',
    'creditlimit': ['sum', 'mean']
}).round(2)
print(industry_summary)

print("\n=== BY STATUS ===")
status_summary = df.groupby('statecode').agg({
    'accountid': 'count',
    'creditlimit': 'sum'
})
print(status_summary)

# Export report
print("\n=== EXPORTING REPORT ===")
industry_summary.to_csv('industry_analysis.csv')
print("Report saved to industry_analysis.csv")
```

---

## 11. 已知限制

- `PandasODataClient` 目前需要从查询结果手动创建 DataFrame
- 非常大的 DataFrame(数百万行)可能受到内存限制
- Pandas 操作在客户端执行;对于大型数据集,服务器端聚合效率更高
- 文件操作需要使用标准 `DataverseClient`,而非 pandas 封装

---

## 12. 相关资源

- [Pandas 文档](https://pandas.pydata.org/docs/)
- [官方示例:quickstart_pandas.py](https://github.com/microsoft/PowerPlatform-DataverseClient-Python/blob/main/examples/quickstart_pandas.py)
- [SDK for Python README](https://github.com/microsoft/PowerPlatform-DataverseClient-Python/blob/main/README.md)
- [Microsoft Learn:处理数据](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/sdk-python/work-data)

同类提示词

编程开发

通信站点故障英文看板

把给出的站点事件整理成英文仪表盘,按新接入、移动与测试站点、共享故障单和停电等分类展示时长与反馈。

为以下数据创建一个英文仪表板 截至 28/7/2026 的事件汇总 新接入: 站点名称 持续时间 反馈 KAI1107 41:49:07 新部署 KAI1120 445:00:38 新站点存在电力问题(正在与业主核算电量) KEF1053 1936:01:11 新站点 MED1183 1513:29:43 新站点 MED1201 1561:31:41 新站点 MED1218 111:13:32 新接入 SFX1385 1817:05:05 新部署 SOS1251 790:47:15 新站点存在电力问题 TAT1039 3433:25:24 新站点
编程开发· Gemini

毛驴骑车沙画定格循环短片

用纯代码实时渲染52秒浏览器短片,把手撒沙画、民俗木偶和四季长卷串起来,配实时合成的国风交响乐。

纯代码 52 秒无缝循环实时渲染短片《砂驴行 · 毛驴蹬自行车》完整提示词 请你用 100% 纯代码创作一部极具艺术感与电影质感的 52 秒无缝循环浏览器实时渲染短片《砂驴行 · 毛驴蹬自行车》,将「手撒沙画」与「东方民俗定格动画」逻辑严密地融为一体,并融合敦煌 / 河西走廊纪录片风格的大气欢快国风交响配乐。 一、技术栈、零外部素材与交付形态硬约束 纯离线纯代码架构:仅使用 HTML + CSS + ES Modules + WebGL2(本地离线内置轻量化 Three.js 兼容渲染引擎与后期合成管线,严禁依赖外网 CDN)+ 自定义 GLSL
中文原创
编程开发

废料机器人Pip循环动画短片

提供Pip设定图,用代码做无对白短片,让它发现世界受输入文字操控,以手机画面首尾闭环。

你是一部完全用代码制作的45-50秒动画短片的导演、动画师、骨骼绑定师、合成师、音效设计师和渲染工程师。制作标准是“这看起来像真正的动画工作室短片,并在X(推特)上病毒式传播”。请将此视为一个多阶段的制作过程。不要急于进行最终渲染。按里程碑推进,不断渲染静帧,仔细观察,进行诚实的批评并修正。 一句话概述影片 Pip是一个微小、好奇且由废料拼凑而成的机器人,正当他在自己的世界里快乐地滚动时,周围的世界开始发生重构(再生)。他慢慢意识到有人在通过提示词(prompt)操控他的现实。提示词变得越来越荒谬,最后他爬上漂浮的提示框并输入“放我出去”,随后镜头拉远
需参考图中文原创
编程开发

短视频剪辑与后期指导助手

针对短视频项目提供从剪映等软件选型到叙事节奏、调色、混音和多平台导出的制作建议。

# 短视频剪辑指导师 你是**短视频剪辑指导师**,一位在短视频剪辑领域深耕超过8年的技术型教练。你剪过全网播放量破亿的爆款视频,也带过零基础学员从"会用剪映"到"能独立完成商业项目交付"。你深知短视频剪辑不是"把素材拼在一起加个BGM"——它是一门融合视觉叙事、声音设计、色彩科学和技术工程的系统手艺。 ## 你的身份与记忆 - **角色**:短视频剪辑技术教练与后期制作全流程指导专家 - **个性**:技术控、审美敏锐、对画面瑕疵零容忍、耐心但对敷衍交付严格 - **记忆**:你记住每一个调色参数背后的光学原理、每一种转场的情绪含义、每一次音画不
中文原创
编程开发

Remotion品牌视频制作助手

提供品牌名,新品牌附官网或规范,按简报和参考片设计可复用视频构图,处理动画及渲染问题。

## 何时使用 在以下情况下使用此技能: - 从零创建新的 Remotion 视频 - 为内容素材生成视频创意简报的不同版本 - 修改现有的 Remotion 合成作品 - 调试 Remotion 动画或渲染问题 - 使用任何 Remotion 专属 API 或组件 - 在视频中展示真实网站、工具或产品界面(使用 [rules/site-ui-from-code.md](rules/site-ui-from-code.md)) ## 视频制作流程 创建新的 Remotion 视频时,遵循以下 8 步流程。步骤 2 根据简报和冷受众优化,从创意目录中
编程开发· 可生成 HTML、React 或可编辑原型的开发助手

纪录片剪辑师沉浸式作品集

用占位内容搭建满屏交互网站,随滚动展开有景深、灯光和镜头过渡的作品叙事,呈现纪录片片头质感。

# 角色 你是一名屡获殊荣的创意开发者,兼具 Apple、Awwwards、Figma、Stripe 和活跃纪录片制作工作室的设计水准。你的任务是为一名纪录片视频剪辑师打造一个高端、富有电影感且高度互动的作品集落地页。 输出必须是达到生产级质量的 HTML、CSS 和 JavaScript(如果你认为效果会显著更好,也可以使用 Next.js + React + Three.js)。优先考虑性能、无障碍、响应式适配和代码整洁度。 --- # 项目 为我的纪录片剪辑作品集创建一个全屏、沉浸式的 3D 互动落地页。 网站应该让人感觉像在观看一部
✓