基于 python pandas 中其他列的值创建一个新列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45112839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a new column based on values from other columns in python pandas
提问by zrelova
I have a pandas dataframe with one column showing currencies and another showing prices. I want to create a new column that standardizes the prices to USD based on the values from the other two columns.
我有一个 Pandas 数据框,其中一列显示货币,另一列显示价格。我想创建一个新列,根据其他两列的值将价格标准化为美元。
eg.
例如。
currency price
SGD 100
USD 80
EUR 75
the new column would have conditions similar to
新列的条件类似于
if currency == SGD: price = price / 1.37 etc.
如果货币 == 新加坡元:价格 = 价格 / 1.37 等。
so in the end it would look like
所以最后它看起来像
currency price new_price
SGD 100 72.99
USD 80 80
EUR 75 65.22
采纳答案by Jonathan
You could create a dictionary containing all the currency conversions and then divide the price column by currency column mappedto the dictionary.
您可以创建一个包含所有货币换算的字典,然后按映射到字典的货币列划分价格列。
df = pd.DataFrame({'currency': ['SGD', 'USD', 'EUR'],
'price': [100, 80, 75]})
to_usd = {'USD': 1.0, 'SGD': 1.37, 'EUR': 1.15}
df['new_price'] = df.price / df.currency.map(to_usd)
print(df)
Prints:
印刷:
currency price new_price
0 SGD 100 72.992701
1 USD 80 80.000000
2 EUR 75 65.217391