gpt4 book ai didi

python - 使用列名获取列值

转载 作者:行者123 更新时间:2023-11-28 22:19:16 25 4
gpt4 key购买 nike

我有以下数据:

    production_type       type_a       type_b     type_c     type_d     
0 type_a 1.173783 0.714846 0.583621 1
1 type_b 1.418876 0.864110 0.705485 1
2 type_c 1.560452 0.950331 0.775878 1
3 type_d 1.750531 1.066091 0.870388 1
4 type_a 1.797883 1.094929 0.893932 1
5 type_a 1.461784 0.890241 0.726819 1
6 type_b 0.941938 0.573650 0.468344 1
7 type_a 0.507370 0.308994 0.252271 1
8 type_c 0.443565 0.270136 0.220547 1
9 type_d 0.426232 0.259579 0.211928 1
10 type_d 0.425379 0.259060 0.211504 1

我想创建一个新的列、列表或系列来返回列的值。

输出

    production_type       type_a       type_b     type_c     type_d     Results 
0 type_a 1.173783 0.714846 0.583621 1 1.173783
1 type_b 1.418876 0.864110 0.705485 1 0.864110
2 type_c 1.560452 0.950331 0.775878 1 0.775878
3 type_d 1.750531 1.066091 0.870388 1 1
4 type_a 1.797883 1.094929 0.893932 1 1.797883
5 type_a 1.461784 0.890241 0.726819 1 1.461784
6 type_b 0.941938 0.573650 0.468344 1 0.573650

基本上如果它在列 [production_type] 中写入 type_a 我想在列 [Results] 中返回 type_a 的结果。

我试过以下方法:

for i in df:
if i == 'type_a':
print ('type_a')
elif i == 'type_b':
print ('type_b')
elif i == 'type_c':
print ('type_c')
elif i == 'type_d':
print ('type_d')
else:
print('')
print('')

使用结果追加

要生成数据框,请使用以下命令:

list_cols = ['type_a','type_b','type_c']
df = pd.DataFrame(np.random.rand(10, 3), columns = list_cols )
df['production_type']= ['type_a','type_b','type_c','type_d','type_a','type_a','type_b'
,'type_b','type_c','type_d']
df['type_d'] = 1
df['results'] = ''

关于在哪里搜索的任何提示?

最佳答案

您可以为此使用 pd.DataFrame.apply:

df['Results'] = df.apply(lambda row: row.get(row['production_type']), axis=1)

解释

  • pd.DataFrame.apply with axis=1 对每一行应用一个函数,并通过隐式循环提取每一行的组件。
  • 该方法允许匿名 lambda 函数作为参数。
  • 我们可以定义 lambda 函数来从 production_type 列中提取所需的值。

关于python - 使用列名获取列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49895393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com