python - 按顺序为数据框中的多行从列表中分配多个值

标签 python list pandas dataframe

为简单起见,我有一个列表 abc,其中 abc=[a,b,c,d,e]

我想为数据框 DF 中的“文本”列分配这些值,这些值在列“数字”= 2 中具有值。我知道数据框有 5 行满足此条件,例如第 1、2、3 行,4 5. 我想要的是 Value in row1 =a, row2 =b , row3=c, row4 =d ,row5=e 我这样写代码:

 i=0
 for row1 in range(0,len(df)):
     if  df.iloc[row1]['Number']==2:
        df.set_value(df.index[row1], 'Text',abc[i])
        i=i+1

但我收到的是第 1,2,3,4 行的值 5 得到相同的值 e 。 你们能不能给我方法来做到这一点。非常感谢

最佳答案

在不修改太多代码的情况下,我能够使用 enumerate()函数而不是你的 i 循环。我正在使用 Python 3。

import pandas as pd 
import numpy as np 
# create sample dataframe
abc = ['a','b','c','d','e', 'f']
data = {'Text':['foo', 'bar', 'spam', 'eggs', 'ham', 'asdf'],
        'Number':[2, 2, 5, 2, 2, 3]}
df = pd.DataFrame.from_dict(data) 
df = df[['Text', 'Number']] # reordering df
print(df)

# Original question code:
# i=0
# for row1 in range(0,len(df)):
#     if df.iloc[row1]['Number']==2:
#         df.set_value(df.index[row1], 'Text',abc[i])
#         i=i+1

# Pseudocode: 
# if row value for the column 'number' is 2:
#     set the value for the column 'text' at an index to the value for abc[index]
for idx, row1 in enumerate(range(0, len(df))):
    if df.iloc[row1]['Number'] == 2:
        df.set_value(df.index[row1], 'Text', abc[idx])
print(df)

请注意,set_value 已贬值,将在未来的版本中删除。

结果:

    text  number
0     a       2
1     b       2
2  spam       5
3     d       2
4     e       2
5  asdf       3

FutureWarning: set_value is deprecated and will be removed in a future release. Please use .at[] or .iat[] accessors instead

关于python - 按顺序为数据框中的多行从列表中分配多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51051381/

相关文章:

python - 如何计算二维列表中不同条目的数量?

python - 从列表列表生成 pandas 数据框

python - 用 folium 绘制标记是否有限制?

python - 我需要简化当前输出并获得干净的输出结果

python - 在 Python 中创建对称矩阵索引值

python - 从 Azure Databricks 将数据写入 Azure Blob 存储

python - 在没有 numpy 的情况下搜索二维列表

python - 如何通过不相似性而不是相似性进行聚类?使用反欧几里德距离可以接受吗?

python - Pandas :一旦一列达到另一列的某个值,如何返回行值?

python - Pandas 使用来自 df 的值从 df 返回值