[英]Manipulate lists in a pandas data frame column (e.g. divide by another column)
我有一個 pandas 數據框,其中一列包含列表。 我希望將每一行中的每個列表元素除以另一列中的標量值。 在以下示例中,我希望將 a 中的每個元素除以 b:
a b
0 [11, 22, 33] 11
1 [12, 24, 36] 2
2 [33, 66, 99] 3
從而產生以下結果:
a b c
0 [11, 22, 33] 11 [1.0, 2.0, 3.0]
1 [12, 24, 36] 2 [6.0, 12.0, 18.0]
2 [33, 66, 99] 3 [11.0, 22.0, 33.0]
我可以通過以下代碼實現這一點:
import pandas as pd
df = pd.DataFrame({"a":[[11,22,33],[12,24,36],[33,66,99]], "b" : [11,2,3]})
result = {"c":[]}
for _, row in df.iterrows():
result["c"].append([x / row["b"] for x in row["a"]])
df_c = pd.DataFrame(result)
df = pd.concat([df,df_c], axis="columns")
但是對行進行顯式迭代並將結果收集到字典中,將其轉換為 dataframe 然后連接到原始數據框似乎非常低效和不優雅。
有沒有人有更好的解決方案?
在此先感謝和歡呼!
PS :如果您想知道我為什么要將列表存儲在列中:這些是傅立葉變換的結果幅度。
為什么我不為每個頻率使用一列?
zip 兩列,通過product和starmap的組合,將 col a 中的每個條目與其對應的 col b 條目分開,並將迭代器轉換回列表。
from itertools import product,starmap
from operator import floordiv
df['c'] = [list(starmap(floordiv,(product(num,[denom]))))
for num, denom in zip(df.a,df.b)]
a b c
0 [11, 22, 33] 11 [1, 2, 3]
1 [12, 24, 36] 2 [6, 12, 18]
2 [33, 66, 99] 3 [11, 22, 33]
或者,您可以在迭代中只使用 numpy 數組:
df['c'] = [list(np.array(num)/denom) for num, denom in zip(df.a,df.b)]
感謝@jezrael 的建議——所有這些可能都是不必要的,因為 scipy 有FFT功能——看看鏈接,看看它是否有幫助。
我會將列表轉換為 numpy arrays:
df['c'] = df['a'].apply(np.array) / df['b']
您將在 c 列中獲得np.array
。 如果您真的需要列表,則必須將它們轉換回來
df['c'] = df['c'].apply(list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.