常见的python库代码
时间: 2024-04-14 15:10:23 浏览: 76
基于Python语言的共享代码库设计源码
以下是一些常见的Python库及其代码:
1. NumPy
```
import numpy as np
# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5])
# Print the array
print(arr)
# Calculate the mean of the array
mean = np.mean(arr)
print(mean)
```
2. Pandas
```
import pandas as pd
# Create a Pandas DataFrame
df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]})
# Print the DataFrame
print(df)
# Get the mean age
mean_age = df['Age'].mean()
print(mean_age)
```
3. Matplotlib
```
import matplotlib.pyplot as plt
# Create a simple line plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
# Add labels and title
plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('Line Plot')
# Show the plot
plt.show()
```
4. Scikit-learn
```
from sklearn.linear_model import LinearRegression
# Create a linear regression model
model = LinearRegression()
# Train the model on some data
X = [[1], [2], [3], [4], [5]]
y = [2, 4, 6, 8, 10]
model.fit(X, y)
# Use the model to make predictions
print(model.predict([[6]]))
```
5. TensorFlow
```
import tensorflow as tf
# Create a TensorFlow graph
a = tf.constant(5)
b = tf.constant(10)
c = tf.add(a, b)
# Run the graph
with tf.Session() as sess:
result = sess.run(c)
print(result)
```
6. Flask
```
from flask import Flask
# Create a Flask app
app = Flask(__name__)
# Define a route and function
@app.route('/')
def hello_world():
return 'Hello, World!'
# Run the app
if __name__ == '__main__':
app.run()
```
7. Django
```
from django.http import HttpResponse
from django.urls import path
from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
# Define a view function
@csrf_exempt
@require_POST
def hello_world(request):
return HttpResponse('Hello, World!')
# Define the URL route
urlpatterns = [
path('hello/', hello_world),
]
# Run the app
if __name__ == '__main__':
from django.core.management import execute_from_command_line
execute_from_command_line(['manage.py', 'runserver'])
```
阅读全文