【问题标题】:How to iterate over dataframe rows, replacing values from a matching tuple in a more pythonic way?如何迭代数据帧行,以更 Python 的方式替换匹配元组中的值?
【发布时间】: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


    【解决方案1】:

    使用map

    z = dict(zip(x,y))
    df['Number'] = df['Number'].map(z)
    

          Strings  Number
    0        some     345
    1      random     363
    2       stuff     371
    3       which     359
    4          is     387
    5  irrelevant     391
    

    要仅映射 一些 值并避免使用 NaN,请使用 replace

    df['Number'] = df['Number'].replace(z)
    

    【讨论】:

      猜你喜欢
      • 2018-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 2016-05-05
      • 1970-01-01
      相关资源
      最近更新 更多