【问题标题】:How can I return values from a given list using a function in pandas?如何使用 pandas 中的函数从给定列表中返回值?
【发布时间】:2021-09-01 02:56:09
【问题描述】:

我有一个将华氏温度转换为摄氏度的功能

def temp_to_celcius(temp):
    return ((temp-32.0)*5.0)/9.0

它从包含华氏温度列表的 DataFrame 中获取一列,例如:

table['temp'][:5]

0    30.0
1    30.0
2    30.0
3    30.0
4    30.0
Name: temp, dtype: float64

并返回修改后的温度列表:

temp_to_celcius(table['temp'][:5])
    
0   -1.111111
1   -1.111111
2   -1.111111
3   -1.111111
4   -1.111111
Name: temp, dtype: float64

但是我怎样才能修改我的函数,以便将第二列中的 values 作为这样的列表返回:

[-1.11111111 -1.11111111 -1.11111111 -1.11111111 -1.11111111]

但不是带有温度列表的索引列?

【问题讨论】:

    标签: python pandas list dataframe function


    【解决方案1】:

    pandas'DataFrame 列是pandas.Series,您可以只提供pandas.Series 作为list 的参数以获取plain 列表,请考虑以下示例:

    import pandas as pd
    df = pd.DataFrame({'col1':[1,2,3]})
    def triple(x):
        return list(x*3)
    triple_values = triple(df['col1'])
    print(triple_values)
    

    输出

    [3, 6, 9]
    

    或者使用pandas.Series'.tolist方法

    import pandas as pd
    df = pd.DataFrame({'col1':[1,2,3]})
    def triple(x):
        return (x*3).tolist()
    triple_values = triple(df['col1'])
    print(triple_values)
    

    输出

    [3, 6, 9]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多