如何在datafram中的所有列上使用相同的函数(来自模块)

2024-05-16 02:57:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试对数据帧上的所有列(0除外)使用相同的函数。在我的数据框架中,我有很多列,如果尝试编写相同的代码,我将花费数年时间。你知道吗

代码的结果:https://imgur.com/a/YuQLaNY

CSV文件:http://www.sharecsv.com/s/23d52aa16dda504c3c20a8f37ea5daeb/file_1.csv

注:我是一个编程(编码)初学者,所以请简单的答案

我写了一些代码,你可以在下面找到。你知道吗

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import peakdetect as pkd

# Importing the Data:

df = pd.read_csv("file_1.csv")

# Min & Max
# Loop (this is for small number of columns)

_mx1, _mn1 = pkd.peakdetect(df["y1"], df["x"], 3, 0.20)

_xm1 = [p[0] for p in _mx1]
_ym1 = [p[1] for p in _mx1]
_xn1 = [p[0] for p in _mn1]
_yn1 = [p[1] for p in _mn1]

_mx2, _mn2 = pkd.peakdetect(df["y2"], df["x"], 3, 0.20)

_xm2 = [p[0] for p in _mx2]
_ym2 = [p[1] for p in _mx2]
_xn2 = [p[0] for p in _mn2]
_yn2 = [p[1] for p in _mn2]

_mx3, _mn3 = pkd.peakdetect(df["y3"], df["x"], 3, 0.20)

_xm3 = [p[0] for p in _mx3]
_ym3 = [p[1] for p in _mx3]
_xn3 = [p[0] for p in _mn3]
_yn3 = [p[1] for p in _mn3]

_mx4, _mn4 = pkd.peakdetect(df["y4"], df["x"], 3, 0.20)

_xm4 = [p[0] for p in _mx4]
_ym4 = [p[1] for p in _mx4]
_xn4 = [p[0] for p in _mn4]
_yn4 = [p[1] for p in _mn4]

d_y_mx = pd.DataFrame(list(zip(_ym1, _ym2, _ym3, _ym4)))

Tags: csv代码inimportdfforaspd
2条回答

试试这个:

def func(x):
    _mx4, _mn4 = pkd.peakdetect(x, df["x"], 3, 0.20)
    _ym4 = [p[1] for p in _mx4]
    return _ym4

d_y_mx = df[df.columns[1:]].apply(func)

它应该已经是一个数据帧了。但要将其更改为数据帧,可以执行以下任一操作:

d_y_mx = pd.DataFrame(d_y_mx)

或者像LazyCoder建议的那样:

d_y_mx = d_y_mx.to_frame()

希望这有帮助。我跳过了其他变量,因为我假设只有d\u y\u mx才是您要查找的变量。你知道吗

_ym = [] #Initialize to be empty list for now.
for y in ('y1','y2','y3','y4'): # Loop over all the y combinations
    _mx,_mn = pkd.peakdetect(df[y], df["x"], 3, 0.20) # Run what I assume is some form of min/max getter.
    _ym.append([p[1] for p in _mx])# append to the list.
d_y_mx = pd.DataFrame(list(zip(tuple(_ym))) # Extract the required data.

相关问题 更多 >