贾里德上面说的是我认为最好的方式,我只是想补充一点,这也解决了问题中提到的速度问题。使用以下速度测试
import pandas as pd
import numpy as np
import timeit
# Create a large dataframe
data = {
"Set_One": ["foo", None, "foo"] * 100000,
"Set_Two": [None, "bar", "bar"] * 100000,
}
df = pd.DataFrame(data)
# Method 1: Using df.apply
def method1():
result = df.apply(lambda x: x.Set_One or x.Set_Two, axis=1)
# Method 2: Using np.logical_or
def method2():
result = np.logical_or(df["Set_One"], df["Set_Two"])
# Measure execution time for method 1
time_method1 = timeit.timeit(method1, number=10)
# Measure execution time for method 2
time_method2 = timeit.timeit(method2, number=10)
print("Time taken using df.apply(lambda x: x.Set_One or x.Set_Two):", time_method1)
print(
'Time taken using np.logical_or(df["Set_One"], df["Set_Two"]):', time_method2)
times_faster = time_method1 / time_method2
print("Method 2 is", times_faster, "times faster than method 1")
我得到以下结果
Time taken using df.apply(lambda x: x.Set_One or x.Set_Two): 20.352213299999903
Time taken using np.logical_or(df["Set_One"], df["Set_Two"]): 0.05363929999998618
Method 2 is 379.4272725409382 times faster than method 1