【发布时间】:2020-04-30 15:17:12
【问题描述】:
我可以通过遍历行来替换 pandas 数据帧的特定列中的值,并将这些值与元组列表中包含的相应元组对匹配。
但是,当我在大型数据帧上运行此代码时,它会变得相对较慢,因为它必须遍历整个元组列表才能找到数据帧中行的匹配项。 (12280it [23:21, 8.66it/s])
有没有更 Pythonic 的方式来进行匹配和替换?例如索引元组列表,以及一些按索引过滤的代码?
我使用的代码可以在下面找到。
import pandas as pd
from tqdm import tqdm
# initialize list of lists
data = [['some', 1], ['random', 10], ['stuff', 14],['which',8],['is',22],['irrelevant',24]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Strings', 'Number'])
df
Strings Number
0 some 1
1 random 10
2 stuff 14
3 which 8
4 is 22
5 irrelevant 24
#Create lists necessary to make tuples
x = list(range(1, 25))
y = list(range(345, 395, 2))
#Create tuple
z = list(zip(x,y))
#Replace number values in dataframe
#With corresponding values from tuple
for index, row in tqdm(df.iterrows()):
for x in z:
if row["Number"] ==x[0]:
df.set_value(index,"Number", int(x[1]))
结果
df
Strings Number
0 some 345
1 random 363
2 stuff 371
3 which 359
4 is 387
5 irrelevant 391
【问题讨论】:
标签: python pandas loops dataframe optimization