我有两个 Pandas DataFrames/Series,每个包含一行。
df1 = pd.DataFrame([1, 2, 3, 4])
df2 = pd.DataFrame(['one', 'two', 'three', 'four'])
Run Code Online (Sandbox Code Playgroud)
我现在想将所有可能的组合放入一个 n*n 矩阵/DataFrame 中,所有交叉产品的值都是自定义函数的输出。
def my_function(x, y):
return f"{x}:{y}"
Run Code Online (Sandbox Code Playgroud)
因此,这应该导致:
df = pd.DataFrame([['1:one', '2:one', '3:one', '4:one'],
['1:two', '2:two', '3:two', '4:two'],
['1:three', '2:three', '3:three', '4:three'],
['1:four', '2:four', '3:four', '4:four']])
0 1 2 3
0 1:one 2:one 3:one 4:one
1 1:two 2:two 3:two 4:two
2 1:three 2:three 3:three 4:three
3 1:four 2:four 3:four 4:four
Run Code Online (Sandbox Code Playgroud)
虽然我可以通过 构建我自己的矩阵itertools.product,但对于较大的数据集,这似乎是一种非常低效的方式,我想知道是否有更 Pythonic 的方式。先感谢您。
我有一个带有垂直数据的相当简单的带状图。
planets = sns.load_dataset("planets")
sns.stripplot(x="method", y="distance", data=planets, size=4, color=".7")
plt.xticks(rotation=45, ha="right")
plt.show()
Run Code Online (Sandbox Code Playgroud)
我想将每个 x 元素 ( ) 的平均值绘制method为一个小水平条,类似于您得到的结果:
sns.boxplot(
x="method",
y="distance",
data=planets,
whis=[50, 50],
showfliers=False,
showbox=False,
showcaps=False
)
Run Code Online (Sandbox Code Playgroud)
但没有第一/第三四分位数的垂直线(whis=[50,50]只有点),并且显示平均值而不是中位数。也许有一个更优雅的解决方案,不涉及箱线图。
我正在执行图像分析并以布尔值的形式生成种子array:
import numpy as np
# Example output array
a = np.array([[False, False, False], [False, True, False], [False, False, False]])
>>> a
array([[False, False, False],
[False, True, False],
[False, False, False]])
Run Code Online (Sandbox Code Playgroud)
由于我想对值周围的区域进行后续分析True,因此我想将其扩展(按一定数量,例如像素)。这将导致以下结果:
>>> a
array([[False, True, False],
[True, True, True],
[False, True, False]])
Run Code Online (Sandbox Code Playgroud)
有没有任何function简单的方法可以解决我的“径向扩展”问题?
预先感谢,BBQuercus
我想知道是否有可能在对满足条件的另一列的值进行计数时对一列进行分组。因为我的数据集有点奇怪,所以我创建了一个类似的数据集:
import pandas as pd
raw_data = {'name': ['John', 'Paul', 'George', 'Emily', 'Jamie'],
'nationality': ['USA', 'USA', 'France', 'France', 'UK'],
'books': [0, 15, 0, 14, 40]}
df = pd.DataFrame(raw_data, columns = ['name', 'nationality', 'books'])
Run Code Online (Sandbox Code Playgroud)
说,我想按国籍分组,并计算该国没有任何书籍(书籍== 0)的人数。
因此,我希望输出类似以下内容:
nationality
USA 1
France 1
UK 0
Run Code Online (Sandbox Code Playgroud)
我使用过滤器,agg尝试了groupby的大多数变体,但似乎什么也没用。
在此先感谢,BBQuercus :)
我对深度学习很陌生,所以请原谅我这个可能很简单的问题。
我训练了一个网络来对positive和进行分类negative。为了简化图像生成和拟合过程,我使用了ImageDataGenerator和fit_generator函数,如下所示:
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# Simplified model
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(12, 12, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
# Image import, for 'validation_generator' equally
train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
'./training/',
target_size=(12, 12),
batch_size=128,
class_mode='binary')
# Compiling
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['acc'])
# Fitting, for Tensorboard 'history = model.fit_gen...'
model.fit_generator(train_generator,
steps_per_epoch=8,
epochs=50,
verbose=1,
validation_data = validation_generator,
validation_steps=8,
callbacks=[tb]) # Standard Tensorboard
Run Code Online (Sandbox Code Playgroud)
我想使用我的模型来预测单个图像(导入为 …
我正在尝试分离近距离的物体,如 U-Net 论文(此处)所示。为此,生成可用于像素级损失的权重图。以下代码描述了我在这篇博文中使用的网络。
x_train_val = # list of images (imgs, 256, 256, 3)
y_train_val = # list of masks (imgs, 256, 256, 1)
y_weights = # list of weight maps (imgs, 256, 256, 1) according to the blog post
# visual inspection confirms the correct calculation of these maps
# Blog posts' loss function
def my_loss(target, output):
return - tf.reduce_sum(target * output,
len(output.get_shape()) - 1)
# Standard Unet model from blog post
_epsilon = tf.convert_to_tensor(K.epsilon(), np.float32)
def …Run Code Online (Sandbox Code Playgroud) 我有两个带有坐标数的 numpy 数组n(每行两个项目)。
coords_a = np.random.random((20, 2))
coords_b = np.random.random((20, 2))
Run Code Online (Sandbox Code Playgroud)
现在,对于每个行组合,我想计算一个函数并将返回值保存为矩阵中的项目。因此,生成的数组应该具有形状(20, 20)并且可以“延迟”计算,如下所示。作为示例性函数,使用欧几里德距离。
def euclidean_dist(x1: float, y1: float, x2: float, y2: float) -> float:
"""Return the euclidean distance between two the points (x1, y1) and (x2, y2)."""
return np.sqrt(np.square(x1 - x2) + np.square(y1 - y2))
matrix = []
for a in coords_a:
row = []
for b in coords_b:
row.append(euclidean_dist(*a, *b))
matrix.append(row)
matrix = np.array(matrix)
Run Code Online (Sandbox Code Playgroud)
正如您可以想象的那样,这个嵌套的 for 循环非常耗时,仅处理 2000 个坐标对就花费了 25 秒以上。是否有推荐的方法来向量化这种叉积?
提前致谢。
python ×7
keras ×2
numpy ×2
pandas ×2
arrays ×1
boxplot ×1
data-science ×1
dataframe ×1
matplotlib ×1
seaborn ×1
swarmplot ×1
tensorflow ×1