将Python Pandas输出添加到现有数据框的列中。

huangapple go评论67阅读模式
英文:

Add Python Pandas output in a column in existing dataframe

问题

你可以使用以下代码将输出保存到现有数据框中的新列中:

df['New_Column_Name'] = x

请将'New_Column_Name'替换为你希望新列的名称。

英文:

I have a csv file which I am reading through pandas

Here's my code

import pandas as pd
df=pd.read_csv(filename.csv)
x=100*df['Country'].value_counts(normalize=True).to_frame()
print(x)

Here's my output

Country
US 45
France 20
Germany 35

I want to save this output in a new column in the existing dataframe .How can I do that?

答案1

得分: 1

使用 Series.map

df['new'] = df['Country'].map(100*df['Country'].value_counts(normalize=True))

示例

df = pd.DataFrame({'Country':['US','US','France','US']})

df['new'] = df['Country'].map(100*df['Country'].value_counts(normalize=True))
print (df)
  Country   new
0      US  75.0
1      US  75.0
2  France  25.0
3      US  75.0
英文:

Use Series.map:

df['new'] = df['Country'].map(100*df['Country'].value_counts(normalize=True))

Sample:

df = pd.DataFrame({'Country':['US','US','France','US']})

df['new'] = df['Country'].map(100*df['Country'].value_counts(normalize=True))
print (df)
  Country   new
0      US  75.0
1      US  75.0
2  France  25.0
3      US  75.0

答案2

得分: 0

I hope, it works for your solution

import pandas as pd
df=pd.read_csv('countries.csv')
df['New Col'] = 100*df['Country'].value_counts(normalize=True).values
df
英文:

I hope, it works for your solution

import pandas as pd
df=pd.read_csv('countries.csv')
df['New Col'] = 100*df['Country'].value_counts(normalize=True).values
df

huangapple
  • 本文由 发表于 2023年5月17日 17:55:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76270809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定