打印数据框中每个唯一值的值,在for循环中。

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

Print values per unique value from dataframe in a for loop

问题

我有一个附件列表(.pdf 文件)在一个文件夹中,还有另一个包含名称和数值的数据框。如果名称有多个值,每个名称可能有多行。

我想要在循环中打印出与每个名称对应的值。

df = pd.DataFrame(data = {'Name': ["Peter", "Peter", "Peter", "Jack", "Jack"], 
                        'Value': ['a', 'b', 'c', 'a', 'nan']})

我尝试了以下两个循环:

for i in df['Name'].unique():
    print(df['Value'][df['Name'] == i], '\n')

for i, j in df.groupby('Name'):
    print(df['Value'][df['Name'] == i])

其中每个 "打印输出" 都是一个系列。相反,我想要打印出每个名称的每个数据值,但是 "分组"。

例如:

Peter:
a
b
c

next

Jack:
a

希望这个翻译对您有所帮助。

英文:

I have a list of attachments (.pdf files) in a folder and another dataframe with name and values. Each name may have multiple rows if the name has multiple values.

I want to print out the values corresponding to each name in a loop.

df = pd.DataFrame(data = {'Name': ["Peter", "Peter", "Peter", "Jack", "Jack"], 
                          'Value': ['a','b','c','a','nan']})

I tried these two loops:

for i in df0['Name'].unique():
    print(df['Values'][df['Name'] == i], '\n')
    
for i,j in df.groupby('Name'):
    print(df['Values'][df['Name'] == i]) 

where each "printout" is a series. Instead I want to print out each data value for each name but "grouped".

For example:

Peter:
a
b
c

next

Jack:
a

答案1

得分: 1

如果想要每个循环生成一个带有分组名称的单列DataFrame,请使用Series.to_frame

for i, j in df.groupby('Name'):
    print(j['Value'].to_frame(i))

或者:

for i, j in df.groupby('Name')['Value']:
    print(j.to_frame(i))
英文:

If want for each loop one column DataFrame with column name like group name use Series.to_frame:

for i,j in df.groupby('Name'):
    print(j['Value'].to_frame(i))

Or:

for i,j in df.groupby('Name')['Value']:
    print(j.to_frame(i))

huangapple
  • 本文由 发表于 2020年1月6日 15:29:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608222.html
匿名

发表评论

匿名网友

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

确定