英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论